Incorrect syntax near 'INDEX' - sql-server

created Index
CREATE INDEX MasterIndex
ON [Attendance].[dbo].[Attendence] (location,createdby,program,batch,term)
tried query
SELECT *
FROM [Attendance].[dbo].[Attendence] USE INDEX (MasterIndex) WHERE createdby='pravin' and term='Term III' and batch='80' and program='computer' and location='AMD'
error
Incorrect syntax near 'INDEX'. If this is intended as a part of a
table hint,
A WITH keyword and parenthesis are now required.

Use the WITH Clause
SELECT *
FROM [Attendance].[dbo].[Attendence] WITH (INDEX (MasterIndex)) WHERE ...

Related

Sqlite3 calculate the percentages from totals

Question(*):
The total number of cases and deaths as a percentage of the population, for each country (with country, % cases of population, % deaths of population as columns)
I have two tables :
countriesAffected(countriesAndTerritories,geoId,countryterritoryCode,popData2019,continentExp)
victimsCases(dateRep,cases,deaths,geoId)
where primary key(geoid)
I tried to do (*) by this method:
SELECT countriesAndTerritories, (100 *SUM(victimsCases.cases) / popData2019)as "cases" ,(100 * SUM(deaths) / popData2019) as "deaths"
FROM countriesAffected
INNER JOIN victimsCases ON victimsCases.geoId = countriesAffected.geoId
GROUP BY countriesAndTerritories
ORDER BY countriesAndTerritories DESC;
Error: near line 2: near "SELECT countriesAndTerritories": syntax error
But for some reason I get all types of syntax errors, i tried to sort it out but with no results. And not sure where did i went wrong.
If you are getting the error Error: near line 2: near "SELECT countriesAndTerritories": syntax error then the issue is with LINE 1 (perhaps no ; at the end of line 1).
Otherwise your query works albiet probably not as intended (as you may well want decimal places for the percentages).
Consider the following (that shows your SQL with additional SQL added to work as intended (see casesV2 and deathsV2 that utilise CAST to force INTEGER to REAL)).
DROP TABLE If EXISTS victimsCases;
DROP TABLE IF EXISTS countriesAffected;
CREATE TABLE IF NOT EXISTS countriesAffected (countriesAndTerritories TEXT,geoId INTEGER PRIMARY KEY,countryterritoryCode TEXT,popData2019 INTEGER,continentExp TEXT);
CREATE TABLE IF NOT EXISTS victimsCases (dateRep TEXT,cases INTEGER ,deaths INTEGER,geoId INTEGER);
INSERT INTO countriesAffected VALUES
('X',1,'XXX',10000,'?'),('Y',2,'YYY',20000,'?'),('Z',3,'ZZZ',30000,'?')
;
INSERT INTO victimsCases VALUES
('2019-01-01',100,20,1),('2019-01-02',100,25,1),('2019-01-03',100,15,1),
('2019-01-01',30,5,2),('2019-01-02',33,2,2),
('2019-01-01',45,17,3),('2019-01-02',61,4,3),('2019-01-03',75,7,3)
;
SELECT countriesAndTerritories,
(100 *SUM(victimsCases.cases) / popData2019)as "cases", /* ORIGINAL */
(100 * SUM(deaths) / popData2019) as "deaths", /* ORIGINAL */
CAST(SUM(victimsCases.cases) AS FLOAT) / popData2019 * 100 AS "casesV2",
CAST(SUM(victimscases.deaths) AS FLOAT) / popData2019 * 100 as "deathsV2"
FROM countriesAffected
INNER JOIN victimsCases ON victimsCases.geoId = countriesAffected.geoId
GROUP BY countriesAndTerritories
ORDER BY countriesAndTerritories DESC;
DROP TABLE If EXISTS victimsCases;
DROP TABLE IF EXISTS countriesAffected;
The result of the above is :-

Incorrect syntax near the keyword 'as' when doing CAST

I am trying to change the value of the data that comes out of the SQL. Where it usually has the value of 4 in SAL_ClientTypeID, I would like it to say 'Private'. The error I am currently getting is
"Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword
'as'."
Initially I tried the following
CASE
WHEN SAL_ClientTypeID = 4 THEN 'Private'
ELSE SAL_ClientTypeID
END,
but I got this error
"Conversion failed when converting the varchar value 'Private' to data
type int."
SELECT SAL_Account_Ref AS 'Account Ref',
CASE
WHEN SAL_ClientTypeID = 4 THEN cast (sal_clienttypeID as nvarchar(20)) as 'Private'
ELSE SAL_ClientTypeID
END
FROM sales;
I expect the value of output where SAL_ClientTypeID = 4 to be 'Private'
SELECT SAL_Account_Ref AS 'Account Ref',
CASE
WHEN SAL_ClientTypeID = 4 THEN 'Private'
ELSE cast (sal_clienttypeID as nvarchar(20))
END
FROM sales;
There are two problems with your query:
Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'as'.
Comes from having as followed by a string literal, this should be followed by column name:
SELECT SAL_Account_Ref AS Account_Ref
The second error is because you return two datatypes on the case - string if it equals to 4, int otherwise, you should use casting to make sure it's always the same:
SELECT SAL_Account_Ref AS Account_Ref,
CASE
WHEN SAL_ClientTypeID = 4 THEN 'Private'
ELSE cast (sal_clienttypeID as nvarchar(20))
END
FROM sales;
You can't mix datatypes in a CASE... try
SELECT SAL_Account_Ref AS 'Account Ref',
CASE
WHEN SAL_ClientTypeID = 4 THEN 'Private'
ELSE CAST(SAL_ClientTypeID, as nvarchar(20))
END
FROM sales;
There is a datatype priority in tsql. Number types have higher priority than text types. Thus, when your case includes both text like 'Private' and number types like SAL_ClientTypeID, the number overrides. When the case of 'Private' comes, tsql tries to convert it to a number and throws the error you see.
If you are OK with having the SAL_ClientTypeID as text, use one of the other answers. Otherwise, you'll have to rethink your specification.

error converting datatype conversion on single vendoritemnumber in duplicate rows

Sql server query shows error :
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.
Here is the query:
WITH employee AS (
SELECT distinct vendoritemnumber,VendorItemId,
VendorItemDescription,
VendorItemDescriptionAlias,VendorId,BrgItemId,itemconversionFactor,
orderbyuomid,pricebyuomid,vendorcasedescription,manufacturernumber,skunumber,[weight],
averageweight,currentprice,taxable,[status],createddate,inactivedate,lastpurchaseddate,
lastupdatedby,lastupdateddate,vendorpercent,vendorfreight,brandid,pack,size,inventorycategoryid,
binlocation,inventorylocation,inventorystatus,physicalinventoryconversionfactor,stateswhereused,
conceptwhereused,priceupdatedate,size_uom,pack_uom,isdeleted,'' as id,'' itemid,'' as oldprice,
'' as newprice,'' as dateupdated,'' as weekenddate,'' as lastpurdate
FROM VendorItems WHERE BrgItemId=6056)
SELECT * FROM employee
UNION ALL
SELECT '' as ven,v.VendorItemId,
v.VendorItemDescription,v.VendorItemDescriptionAlias,v.VendorId,v.BrgItemId,v.itemconversionFactor,
v.orderbyuomid,v.pricebyuomid,v.vendorcasedescription,v.manufacturernumber,v.skunumber,v.[weight],
v.averageweight,v.currentprice,v.taxable,v.[status],v.createddate,v.inactivedate,v.lastpurchaseddate,
v.lastupdatedby,v.lastupdateddate,v.vendorpercent,v.vendorfreight,v.brandid,v.pack,v.size,v.inventorycategoryid,
v.binlocation,v.inventorylocation,v.inventorystatus,v.physicalinventoryconversionfactor,v.stateswhereused,
v.conceptwhereused,v.priceupdatedate,v.size_uom,v.pack_uom,v.isdeleted,ph.id,ph.itemid,ph.oldprice,
ph.newprice,ph.dateupdated,ph.weekenddate,brg.lastpurchasedate
from [dbo].[VendorItems] v join PriceHistory ph
on ph.ItemId=v.VendorItemId join brgitems brg on
brg.brgitemid=v.BrgItemId
WHERE v.BrgItemId=6056
group by vendoritemnumber,v.VendorItemId,v.VendorItemDescription,v.VendorItemDescriptionAlias,v.VendorId,v.BrgItemId,v.itemconversionFactor,
v.orderbyuomid,v.pricebyuomid,v.vendorcasedescription,v.manufacturernumber,v.skunumber,v.[weight],
v.averageweight,v.currentprice,v.taxable,v.[status],v.createddate,v.inactivedate,v.lastpurchaseddate,
v.lastupdatedby,v.lastupdateddate,v.vendorpercent,v.vendorfreight,v.brandid,v.pack,v.size,v.inventorycategoryid,
v.binlocation,v.inventorylocation,v.inventorystatus,v.physicalinventoryconversionfactor,v.stateswhereused,
v.conceptwhereused,v.priceupdatedate,v.size_uom,v.pack_uom,v.isdeleted,ph.id,ph.itemid,ph.oldprice,
ph.newprice,ph.dateupdated,ph.weekenddate,brg.lastpurchasedate
I want to show single vendoritemnumber in duplicate rows..Any suggestion??
Where is the error??
SQL Server cannot convert an empty string to NUMERIC data type. For example, the following will yield the same error:
SELECT CONVERT(NUMERIC, '')
Replace empty strings ('') with 0 or NULL.
#manoj .Just FYI to know exact error point , double click on the error in message window .It shows the exact line of code on error, Also try to check if any empty values are there for that column and as mentioned by #Serge SQL throws error while any data type is converted to numeric and if its value is empty. Best solution is to add WHERE clause and filter those cases.

Convert Statement to Crystal Reports SQL Expression

I have a SQL command that works great in SQL Server. Here's the query:
SELECT TOP 1000
(
SELECT COUNT(LINENUM)
FROM OEORDD D1
WHERE D1.ORDUNIQ = OEORDD.ORDUNIQ
)
- (SELECT COUNT(LINENUM)
FROM OEORDD D1
WHERE D1.ORDUNIQ = OEORDD.ORDUNIQ
AND D1.LINENUM > OEORDD.LINENUM)
FROM OEORDD
ORDER BY ORDUNIQ, LINENUM
The query looks at the total lines on an order, then looks at the current "LINENUM" field. With the value of the LINENUM field, it looks to see how many lines have a greater LINENUM value on the order and subtracts it from the number of lines on an order to get the correct Line number.
When I try to add it as a SQL expression in version 14.0.2.364 as follows:
(
(
SELECT COUNT("OEORDD"."LINENUM")
FROM "OEORDD" "D1"
WHERE "D1"."ORDUNIQ" = "OEORDD"."ORDUNIQ"
)
- (SELECT COUNT("OEORDD"."LINENUM")
FROM "OEORDD" "D1"
WHERE "D1"."ORDUNIQ" = "OEORDD"."ORDUNIQ"
AND "D1"."LINENUM" > "OEORDD"."LINENUM"
)
)
I get the error "Column 'SAMDB.dbo.OEORDD.ORDUNIQ' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
If I try to add GROUP BY "OEORDD"."ORDUNIQ" at the end, I get "Incorrect syntax near the keyword 'GROUP'. I've tried adding "FROM OEORDD" at the end of query and it errors out on the word "FROM". I have the correct tables linked in the Database Expert.
EDIT --------------
I was able to get the first query working by getting rid of the alias, it's as follows:
(
SELECT COUNT(LINENUM)
FROM OEORDD
WHERE OEORDH.ORDUNIQ=OEORDD.ORDUNIQ)
)
However, I believe I need to use the alias in the second query to compare line numbers. I'm still stuck on that one.

Msg 102, Level 15, State 1 Incorrect syntax near '>'

I have a SQL Server Procedure like this:
//Beginning of procedure
SELECT
CASE IDNumber
WHEN (DATALENGTH(IDNumber)>7)
THEN SUBSTRING(IDNumber,0,6)
WHEN (DATALENGTH(IDNumber) < 7)
THEN CONCAT((REPLICATE(0,7-LEN(IDNumber)),IDNumber)
END AS NID
//Rest of the procedure here
the code on execution throws the error Incorrect syntax near '>'. on line WHEN (DATALENGTH(IDNumber)>7) .
IDNumber is a nvarchar. I tried using LEN(IDNumber) but in vain.
I don't know what the error is!
Rewrite your query like that:
SELECT CASE
WHEN DATALENGTH(IDNumber) > 7 THEN SUBSTRING(IDNumber, 0, 6)
WHEN DATALENGTH(IDNumber) < 7 THEN CONCAT(REPLICATE(0, LEN(IDNumber)), IDNumber)
END AS NID;
When you write CASE Column, you have to compare it to direct values, not to an expression.
If you have case variable then you need to provide values to When part, not the condition

Resources