SQL query error in a stored procedure in Microsoft SQL Server 2012 - sql

I am getting this error:
Incorrect syntax near the keyword 'set'.
Here is the code snippet
'Update ' + #TableName +' set status='+str(#status)+ ' where id in (Select Sid from '+#tname+' where SiteId=' + str(#SiteId) + ' and OtId = '+str(#OtId) + ' and (coalesce(VID,'''')='''' OR VID = ''' + #VID +'''))'

You are likely getting leading white spaces using the STR() function without specifying the length and this is causing an error. For example select str(1) returns 1 with 9 padded spaces.
What also could be happening is that #status is > 10. In this case it will be truncated to ****. For example,select str(12345678910) returns ***.
So, don't use STR() for this. Use CAST() or CONVERT(). Granted this may not be your only issue, but I suspect it is based on what you have provided. I would read the comments, as I agree that you have not given sufficient information to debug this code. Pay close attention to #Back's comment and use PRINT(#yourQuery) next time
MSDN on STR()
The specified length should be greater than or equal to the part of
the number before the decimal point plus the number's sign (if any). A
short float_expression is right-justified in the specified length, and
a long float_expression is truncated to the specified number of
decimal places. For example, STR(12,10) yields the result of 12. This
is right-justified in the result set. However, STR(1223,2) truncates
the result set to **.

Related

SQL Error in Non Case condition of CASE WHEN clause

I tried executing the following SQL statement.
SELECT CASE WHEN CHARINDEX('~','test.pdf') > 0
THEN SUBSTRING('test.pdf',CHARINDEX('~', 'test.pdf'), -10)
ELSE NULL
END
This resulted in an error 'Invalid length parameter passed to the substring function.'. However, this was not expected because it is not going to execute anyway.
This query is a simplified version of my requirement. Actually we are computing the value length for the substring. The real scenario is also given below :
SELECT CASE
WHEN CHARINDEX('~', 'test.pdf') > 0 THEN SUBSTRING('test.pdf', CHARINDEX('~', 'test.pdf') + 1, CHARINDEX('~', 'test.pdf', (CHARINDEX('~', 'test.pdf', 1)) + 1) - CHARINDEX('~', 'test.pdf') - 1)
ELSE NULL
END;
In the example its hardcoded as 'test.pdf' but in real scenario it would be values like '111111~22222~33333~4444.pdf' from Table column. Also, I'm not sure this file name should always follow this format. Hence, a validation is required.
Actually, the computation for length is quite expensive, and don't want to use it twice in this query.
You have passed -10 as a constant to substring(). This function does not allow negative values for the third argument:
length
Is a positive integer or bigint expression that specifies how many characters of the expression will be returned. If length is negative, an error is generated and the statement is terminated. If the sum of start and length is greater than the number of characters in expression, the whole value expression beginning at start is returned.
SQL Server catches this problem during the compile phase. This has nothing to do with CASE expression evaluation, but with parsing the expressions.

Error when a field is declared as NULL in where clause

We have a query running on sybase and we get the below error for certain account numbers but works for others
sqlanywhere error 1009145: Data type conversion not possible integer(10,0) to varchar(6,0)
(oselib/hos_dfe.cxx 13811)
So i started debugging it and found out the error was coming from a field in the format of an int( values are like 20,200,721). This field is declared as NULl in the where statment like FieldA is NULL.
So when i changed to STR(FieldA) it started to work and it all good now.
But my question is why would that cause the above error. Its an integer and the statement is only checking for values which are null and the values in the db are [NULL].
Any ideas why that is happening with this field?
This is NOT an integer: '10,000'. It is a string with digits and commas.
This is NOT an integer: '10000'. It is a string with just digits.
Sybase can only convert strings that are all digits to integers, and commas are not digits. (Okay, it can also handle leading negative signs too.) You can remove the commas using replace():
cast(replace(col, ',', '') as int)

SQL Server - Combine string to integer where integer can have a variable number of leading zeros

I have a report in SQL Server Report Builder which brings back the profession acronym (string) and registration number (integer) for each professional in a separate SQL database.
The registration number can be 5 or more digits long, and may start with one or more zeros. For example:
Profession Registration #
AB 00162
PH 02272
SA 13925
SA 026025
DA 1025927
I'm trying to put the profession acronym and registration number together into a registration ID, because I need to compare this with the registration ID from another (non SQL) database.
I'm trying to get something like this:
Registration ID
AB00162
PH02272
SA13925
SA026025
DA1025927
I've tried converting the integers to strings using the following in my query:
REGISTRY.PROFESSION + right('00000' + cast(REGISTRY.REGISTRATION_NO as varchar(8)), 5) as Full_Reg_Number
However, with the above the integers that are more than 5 digits long get cut off, and if I increase '00000' to, say, '0000000' and the number '5' to '7' in the above, the integers that only have 5 digits are padded with extra leading zeros.
I do not have permission to change the formatting of the integers in either database.
Integers aren't stored with leading zeroes. To be stored like that, then the field is NOT of integer type in the first place. Simply do:
Registry.profession + registry.registration_no
You can confirm that the stored type is not an integer as follows:
select data_type
from information_schema.columns
where table_name = 'registry'
and column_name = 'registration_no'
If you're getting a type conversion error as you mention in your comments, then most likely the error is not coming due to this concatenation. It's probably down the line, such as if you're using 'Full_Reg_Number' in a 'where' statement or other comparison that expects a comparison to an integer, and instead is getting a varchar. After all, you called the column 'Full_Reg_Number' even though it's not a number.
Based on your problems, I suspect those really are integers. You've just shown them with leading zeros in the question.
A simple solution is to use case:
(REGISTRY.PROFESSION +
CASE WHEN REGISTRY.REGISTRATION_NO < 10000 THEN right('00000' + cast(REGISTRY.REGISTRATION_NO as varchar(8)), 5)
ELSE REGISTRY.REGISTRATION_NO
END
) as Full_Reg_Number
An even simpler method uses FORMAT():
(REGISTRY.PROFESSION + FORMAT(REGISTRY.REGISTRATION_NO, '00000')
) as Full_Reg_Number

Access query vs SQL Server 2008 query

I'm trying to convert this query from an Access db to work in SQL Server 2008 and got stuck. I know there are differences, but I'm not sure what's going on and apparently I'm not very good at this.
Any help would be appreciated.
Access
Mid(Trim([SC01039]),
InStrRev(Trim([SC01039])," ")+3,4)
AS ProductType
SQL Server 2008 (This is what I tried changing it to)
Substring(RTrim(LTrim([SC01039])),
Right(RTrim(LTrim([SC01039])),
CHARINDEX(' ',RTrim(LTrim([SC01039]))))+3,4)
AS ProductType
The error I receive is
"Conversion failed when converting the nvarchar value 'L318' to data
type int."
Why is it trying to convert the resulting text into an integer? My assumption is the query is saying, "Find the position of the space closest to the right of the string, now add 3 to that position and give me the next 4 characters." It seems to be a problem with the data, not the query (what does it do if there is no space? Or the string is null?) I dunno...
Did I even get close? :P
There are mixed characters in SC01039, but this is a sample:
SC01039 : Expected Output
------------- : ---------------
QC 06999911 : 9999
SW 12FMT116 : FMT1
26RMF399 : RMF3
08 : [empty]
[empty] : [empty]
Apparently it is always 4 characters, starting 3 to the right of the first space found (searching for the space from right-to-left). Some data in SC01039 have multiple spaces (ie: 09 TVR 012 2, in this case it doesn't return anything and I believe that is OK).
You problem is with Right(RTrim(LTrim([SC01039])), part of your code. Why do you need it? Because what I've shown below should do the trick.
Try this:
Substring(RTrim(LTrim([SC01039])),
CHARINDEX(' ',RTrim(LTrim([SC01039])))+3,4)
AS ProductType
The Substring is expecting SUBSTRING(expression, start, length) and you provided the second parameter with a nvarchar;
Right(RTrim(LTrim([SC01039])),
CHARINDEX(' ',RTrim(LTrim([SC01039]))))+3
hence your error.
Create this function (you don't have to put it helps with readability
CREATE FUNCTION InStrRev(#Val nvarchar(max), #substr nvarchar(max))
RETURNS int
AS
BEGIN
RETURN CASE WHEN CHARINDEX(#substr, RTrim(LTrim(Reverse(#Val)))) = 0 THEN 0 ELSE LEN(#Val) - CHARINDEX(#substr, RTrim(LTrim(Reverse(#Val)))) + 1 END -- add one because you want a start position
END
and use it in your code like this
Substring(RTrim(LTrim([SC01039])), dbo.InStrRev([SC01039], ' ') + 3, 4) AS ProductType
Hope it helps

add zero and convert as varchar to a flot using a single query

I have data where I need to add leading zeros to it. But the problem is the data type is float. So whenever I add zeros, it automatically omits them. I have tried to add leading zero to it then try to convert it to varchar(50). But the it is giving an error:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'wallet_sys'.
I have used following query:
select (convert (varchar(50), ('0' + wallet_sys wallet_sys))) from NewSysData1
What have I done wrong?
PS: Some of the sample data are below: 17187383, 87339833, 93838793
I want these to be: 017187383, 087339833, 093838793
You have to add the zero after it's become a string, not before:
select '0' + convert (varchar(50), (wallet_sys)) as wallet_sys from NewSysData1
Normally, most people want to convert to having, say, a fixed width of result, with the appropriate number of leading zeros to make that happen. For that, it's a bit more work:
select RIGHT('0000000000' + convert (varchar(50), (wallet_sys wallet_sys)),10) as wallet_sys
from NewSysData1
Will produce 10 digits, with as many leading zeroes as needed (The number of zeroes in the string literal should be ~equal to the number of desired digits, and this is also the 10 provided at the right hand end of the first line)