SQL error: conversion failed when converting nvarchar value - sql

I am attempting to write a fairly simple stored procedure but getting an error when I print #sql
set #where = ' where deliverydate between '''+ #FromDate + ''' and ''' + #ThruDate + ''''
set #where = #where + ' and custlocation = '+ #custlocationID + ''''
The error reads:
Conversion failed when converting the nvarchar value ' where deliverydate between '8/1/2013' and '8/20/2014' and custlocationID = ' to data type int.
#custlocationID is declared as int.
Can someone help with the apostrophes?

It's not the apostrophes that causes the error message. You are trying to add a string and an integer, and that will implicily convert the string to an integer.
Cast the integer to a string before you concatenate them:
set #where = #where + ' and custlocation = ' + cast(#custlocationID as varchar)

Related

Comparing string with an UNIQUEIDENTIFIER?

I have written the following procedure:
ALTER PROCEDURE [dbo].[GetLocationOfGuidPre]
#GuidArgument UNIQUEIDENTIFIER
.
.
.
SET #SQL_String = 'INSERT INTO #Guids(FoundGuid) SELECT ' + #ColName + ' FROM ' + #TableSchema + '.' + #TableName + ' WHERE ' + #ColName + ' = ' + #GuidArgument;
When I try to execute it, I get this error:
The data types nvarchar and uniqueidentifier are incompatible in the add operator.
How can I compare a string value with UNIQUEIDENTIFIER?
Have you tried passing it as a parameter?
SET #SQL_String = 'INSERT INTO #Guids(FoundGuid) SELECT ' + #ColName + ' FROM ' + #TableSchema + '.' + #TableName + ' WHERE ' + #ColName + ' = #GuidArgument';
EXEC sp_executesql #SQL_string,
N'#GuidArgument UNIQUEIDENTIFIER',
#GuidArgument = #GuidArgument;
I guess the reason for this error is pretty clear: it says + ' = ' + #GuidArgument; does not work, since you try to add an unique ID to a varchar... just try to cast your #GuidArgumentas varchar and it should work.

Dynamic query SQL where condition

I want to attach numeric value in dynamic query but I am an getting error:
Conversion failed when converting the varchar value ' + #psRegionCode + ' to data type smallint
My query is:
SET #psRegionCode = UPPER(LTRIM(RTRIM(#psRegionCode)))
IF (#psRegionCode <> 0)
BEGIN
SET #sSQLStr = #sSQLStr + ' ' + 'AND reg.region_cd = ''' + #psRegionCode + ''''
END
Things which I tried:
SET #psRegionCode = UPPER(LTRIM(RTRIM(#psRegionCode)))
IF (#psRegionCode <> 0)
BEGIN
SET #sSQLStr = #sSQLStr + ' ' +
'AND reg.region_cd = ' + cast(#psRegionCode as nvarchar(10) ''
END
Can somone please help me with this?
IF (#psRegionCode <> 0)
BEGIN
SET #sSQLStr = #sSQLStr +
' AND reg.region_cd = ' + cast(#psRegionCode as nvarchar(10))
you need to make sure you have correct number of apostrophes
if #psRegionCode is number, why you ltrim it? if it is a string why you cast it?
Well, by your syntax I'm guessing SQL-Server? Any way I think your second query should work, you are just missing a parenthesis :
IF (#psRegionCode <> 0)
BEGIN
SET #sSQLStr = #sSQLStr +
' AND reg.region_cd = ' + cast(#psRegionCode as nvarchar(10))
END
You can't concat a number into a string without the conversion.

Conversion failed when converting the nvarchar value to data type int

Do you know what could be wrong here?
All variables are nvarchar.
The error occurs when #FunctionValue contains an INT in string format.
IF #TargetType = 'INT'
BEGIN
SELECT #SQLSTR = 'UPDATE ' + #TargetTable +
' SET ' + #TargetColumn + ' = ' + COALESCE(CAST(#FunctionValue AS INT), CAST(#Value AS INT)) +
' '
END
The problem is the ambiguity of the + operator. When any argument is numeric, then it assumes you are doing numeric addition, rather than string concatenation.
If your original data is characters, then you can fix it by removing the cast entirely:
IF #TargetType = 'INT'
BEGIN
SELECT #SQLSTR = 'UPDATE ' + #TargetTable +
' SET ' + #TargetColumn + ' = ' + COALESCE(#FunctionValue, #Value) +
' '
END;
If your original data is numeric, then you need to explicitly convert them to characters:
IF #TargetType = 'INT'
BEGIN
SELECT #SQLSTR = 'UPDATE ' + #TargetTable +
' SET ' + #TargetColumn + ' = ' + cast(cast(COALESCE(#FunctionValue, #Value) as int) as varchar(255)) +
' '
END;
I also moved the "cast to int" outside the coalesce().
You are converting a 'varchar' and an 'int' without explicitly converting the types. When this happens, the data-type with the highest precedence wins. In this case, Int has a higher precedence than a varchar, therefore the whole statement becomes an Int. And converting an int to a varchar inexplicitly is not allowed.
Try wrapping a 'CAST ... as VARCHAR' around your Int values:
CAST(COALESCE(CAST(#FunctionValue AS INT), CAST(#Value AS INT)) AS NVARCHAR(255))
For a list of data-type precedences, see http://technet.microsoft.com/en-us/library/ms190309(v=sql.105).aspx
Hope this helps

best approach to execute a dynamic query inside a SP

I'm having some trouble executing a dynamic query inside my SP, and I thought asking for some help as I can't execute it correctly no matter what I try:
I have tried:
SET #subWorksQuery =
'UPDATE JK_SubscriberWorks SET ' +
'update_date = convert(datetime, ''' + #dateNow + ''', 103), ' +
'challenge_' + convert(nvarchar(2), #challengeDay) + '_q = ''' + #challengeQuestion + ''', ' +
'challenge_' + convert(nvarchar(2), #challengeDay) + '_a = ''' + #challengeAnswer + ''' ' +
'WHERE subscriberwork_id = '' + convert(nvarchar(10), #subscriberWorksId) + '';';
execute #execReturn = #subWorksQuery
but I always get:
Msg 203, Level 16, State 2, Procedure sp_InsertChallengeResponse_test,
Line 112
The name 'UPDATE JK_SubscriberWorks SET update_date = convert(datetime, '23-12-2011 23:35:17', 103), challenge_23_q =
'Hvilket år blev Klasselotteriet omdannet til et aktieselskab? Få hjælp til svaret.',
challenge_23_a = '1992' WHERE subscriberwork_id = ' +
convert(nvarchar(10), #subscriberWorksId) + ';' is not a valid
identifier.
Removing the UPDATE statement from that error and run it independently, it runs and performs the update
If I use sp_executesql like
SET #subWorksQuery =
N'UPDATE JK_SubscriberWorks SET ' +
'update_date = #a, ' +
'challenge_' + convert(nvarchar(2), #challengeDay) + '_q = #b, ' +
'challenge_' + convert(nvarchar(2), #challengeDay) + '_a = #c ' +
'WHERE subscriberwork_id = #d;';
SET #parmDefinition = N'#a datetime, #b nvarchar(250), #c nvarchar(500), #d decimal';
execute sp_executesql
#subWorksQuery,
#parmDefinition,
#a = #CreateDate, #b = #challengeQuestion, #c = #challengeAnswer, #d = #subscriberWorksId;
It never performs the UPDATE, but does not throw any error.
What am I missing here?
Run it like this:
execute (#subWorksQuery)
[you won't be getting anything back from the update statement in the variable, and you can't run like this execute (#execReturn = #subWorksQuery) ]
Without parentheses it seems to be starting parsing, assuming it is a stored procedure name, but failing when it hits the max length for one.
In saying that, it is better to use sp_executesql with parameters.
I am not sure what you are looking for in the return value, but if you just need the count of rows affected, that should be easy to obtain.
Change:
execute #execReturn = #subWorksQuery
to:
execute (#subWorksQuery)
select #execReturn = ##ROWCOUNT
just a thought...your #d parameter is a decimal value. Is your id an int? is there a possible data type conflict?
how are your sp input parameters defined? Could you post the full sp?
Dave

Date conversion error on UPDATE command

I have a stored procedure that is throwing an error on an UPDATE command here are the pertinent lines of code.
DECLARE #submitDate1 DATETIME;
SET #submitDate1 = GETDATE()
SET #sql = 'UPDATE ' + #currTable + ' SET [lang_String] = ''' + #lang_String + ''', [date_Changed] = ''' + #submitDate1 + ''', [prev_LangString] = ''' + #prev_LangString + ''', [needsTranslation] = ''' + #needsTranslation + ''' WHERE [ID] = ' + CAST(#ID as nvarchar(10)) + '; '
EXEC(#sql)
Here is the error...
Conversion failed when converting date and/or time from character string.
You have to convert the date into a string before concatenating it to the other strings:
... = ''' + convert(varchar(20), #submitDate1) + ''', [...
use
convert(varchar,#submitDate1)
at the place where you have used #submitDate1 variable.
SQL does not do implicit conversion from date to string!