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!
Related
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.
I would like to ask how can I add an apostrophe into a dynamic SQL. I need to return an SQL statement in one of the columns which has to have apostrophes in itself.
I have the following statement:
SET #SQL_String = N'INSERT INTO #ReturnTable
(
TableName,
ColName,
SQL_Statement,
Value
)
VALUES
(
''' + #TableName + ''',
''' + #ColName + ''',
''' +
'SELECT ' +
#ColName +
' FROM ' +
#TableSchema + '.' + #TableName +
' WHERE ' +
#ColName + ' = ' + CAST(#GuidArgument AS NVARCHAR(50)) + ';' +''',
(
SELECT
' + #ColName + '
FROM
' + #TableSchema + '.' + #TableName +
' WHERE '
+ #ColName + ' = ''' + CAST(#GuidArgument AS NVARCHAR(50)) +
'''))';
Executing with:
EXECUTE #RC = [dbo].[GetLocationOfGuidPre] 'F2CAB996-F00F-43B8-A67A-0000721A829D'
I need to put a whole first CAST into a pair of '.
I've tried:
Putting whole CAST statement into a separeted variable like: DECLARE #Test NVARCHAR(50);
SET #Test = CAST(#GuidArgument AS NVARCHAR(50));
SET #Test = 'CAST(#GuidArgument AS NVARCHAR(50))';
SET #Test = '''CAST(#GuidArgument AS NVARCHAR(50))''';
Addidng two more apostrophes:
' WHERE ' + #ColName + ' = ''' + CAST(#GuidArgument AS NVARCHAR(50)) + ''';'
Please use CHAR(39) instead of typing ' in your dynamic code directly.
Example:
declare #my_dynamic_sql nvarchar(max) = 'print char(39);';
exec(#my_dynamic_sql);
I have four columns in a table ID, Longitude, Latitude, and SpatialData. I have the first three columns filled out for every row, but I need to enter in the SpatialData for each row. I can currently manually update the SpatialData column by using the below query:
update GioMap set SpatialData = 'Point(-74.009506 40.70602)' Where ID =1
From here I have to keep manually updating the Longitude, Latitude and ID for every row. I am using this code to try to loop through all of the rows and update the table that way:
DECLARE #LoopC INT = 1, #MaxOID INT,
#Long nVarchar(32), #Lat nVarchar(32),#Col1 nVarchar(11)
SET #MaxOID = (select count(*) from GioMap)
Set #Col1 = 'SpatialData'
WHILE(#LoopC <= #MaxOID)
BEGIN
SET #Long = (Select Longitude FROM GioMap where ID = #LoopC)
SET #Lat = (Select Latitude FROM GioMap where ID = #LoopC)
DECLARE #sql VARCHAR(MAX) = ('update GioMap set ' + #Col1 +' = ' + '''' + 'Point(' + #Long + ' ' + #Lat + ')' + '''' + ' Where ID = ' + #LoopC)
EXEC sp_executesql #sql
SET #LoopC = #LoopC + 1
END
When I run this code I keep getting this error message:
Msg 245, Level 16, State 1, Line 13
Conversion failed when converting the nvarchar value 'update [ISSHXI1].[dbo].[GioMap] set SpatialDat = 'Point(-74.0095 40.706)' Where ID = ' to data type int.
I don't understand why it would be trying to convert it to an int?
You could do something like this:
UPDATE GioMap SET SpatialData = 'Point(' + cast(Longitude as varchar) + ' ' + cast(Latitude as varchar) + ')'
I think the way you are doing it is bad, but that's not technically what you asked.
It is trying to convert it to an int because you are adding a varchar to an int. You need to change this:
DECLARE #sql VARCHAR(MAX) = ('update GioMap set ' + #Col1 +' = ' +
'''' + 'Point(' + #Long + ' ' + #Lat + ')' + '''' + ' Where ID = ' +
#LoopC)
to this
DECLARE #sql VARCHAR(MAX) = ('update GioMap set ' + #Col1 +' = ' +
'''' + 'Point(' + #Long + ' ' + #Lat + ')' + '''' + ' Where ID = ' +
Cast(#LoopC as varchar))
The point statement paramaters need to be seperated by a comma.
DECLARE #sql VARCHAR(MAX) = ('update GioMap set ' + #Col1 +' = ' + '''' + 'Point(' + #Long + ' ' + #Lat + ')' + '''' + ' Where ID = ' + #LoopC)
Instead of:
#Long + ' ' + #Lat + ')
try
#Long + ',' + #Lat + ')
To see what is being executed you can try adding a print statement:
DECLARE #sql VARCHAR(MAX) = ('update GioMap set ' + #Col1 +' = ' + '''' + 'Point(' + #Long + ' ' + #Lat + ')' + '''' + ' Where ID = ' + #LoopC)
print #sql
EXEC sp_executesql #sql
Also why do you parans around strings you are assigning? Its confusing in TSQL. While it works it is jarring and unusual.
Instead of:
SET #MaxOID = (select count(*) from GioMap)
try
SET #MaxOID = 'select count(*) from GioMap'
Later in the code you do both parens and quotes. The great, great majority of TSQL developers just use single quotes.
Ben
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)
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