I am trying to perform the below query where some variables are being used. This below SQL code is a part of a stored procedure. Idea is to dynamically set the target columns and its values based on FileKey.
DECLARE #TargetColNames nvarchar(max) = '';
DECLARE #SourceColNames nvarchar(max) = '';
DECLARE #SourceColNamesInsert nvarchar(max) = '';
DECLARE #UpdateColumns nvarchar(max) = '';
SELECT
CASE
WHEN #FileKey IN ('s_1','s_2')
THEN #TargetColNames = #TargetColNames + ' [CreatedUser], [UpdatedUser], [CreatedDateTime],[UpdatedDateTime],[IsDeleted],[DeletedOn]'
ELSE #TargetColNames = #TargetColNames + ' [CreatedUser], [UpdatedUser], [CreatedDateTime], [UpdatedDateTime]'
END,
#SourceColNames = CONCAT('CreatedUser','UpdatedUser','CreatedDateTime', 'UpdatedDateTime'),
#SourceColNamesInsert = CONCAT(''',#User, ''',''',#User, ''', 'Getdate()', 'Getdate()' ),
CASE
WHEN #FileKey IN ('s_1','s_2')
THEN #UpdateColumns = CONCAT('Target.UpdatedUser= ''',#User,''', 'Target.[IsDeleted]=0','Target.[DeletedOn]=null')
ELSE #UpdateColumns = CONCAT('Target.UpdatedUser= ''',#User,''', 'Target.UpdatedDateTime=Getdate()')
END
The above SQL statement throws an error:
Msg 102, Level 15, State 1, Procedure uspDynamicStageToPropLayer1, Line 165 [Batch Start Line 5]
Incorrect syntax near '='.
What am I missing here? Maybe this is quite a silly mistake...
Also, by doing concat with your quoted parts, you might allow SQL injection into your query even building dynamically. What if a user's name (or forced parameter has a leading single quote, then garbage injection such as
#User = ';drop table X --
Having said that, some of the stuff could be more simplified, such as
SELECT
#TargetColNames = #TargetColNames
+ ' [CreatedUser], [UpdatedUser], [CreatedDateTime], [UpdatedDateTime]'
+ CASE WHEN #FileKey IN ('s_1','s_2')
THEN ', [IsDeleted], [DeletedOn]'
else ''
end
For the insert, you will probably get a failure. If you look at a possible result of the #User
#SourceColNamesInsert = concat(''',#User, ''',''',#User, ''',
'Getdate()', 'Getdate()' ),
will result with the value below which is not what I think is intended. Notice no comma's between values because the triple ' is creating start and end literals, and leaves no actual comma between column insert values.
',#User, '',#User, 'Getdate()Getdate()
But instead...
select concat('''#User'', ''#User''', ', Getdate(), Getdate()' );
which will result in...
'#User', '#User', Getdate(), Getdate()
The ''' actually creates an opening quoted string immediately with the value after it, then the '' (double) closes the quoted string, but it also adds the comma separator before the next '' (double) to start second user and ''' (triple) to close the second #User, then adding comma and both getdate() calls.
'#User', '#User', Getdate(), Getdate()
Now, if the value for #User was 'Bob', and your intent was to have the string output as
'Bob', 'Bob', Getdate(), Getdate()
change to
select concat('''', #User, ''', ','''', #User, '''', ', Getdate(), Getdate()' );
The '''' (quad) means I want to open a string, do a single quote (by the inner two ''), and close this as its own string. then get the value of the #User. Then follow by an open string ' with '' for closing the quote around the name, then open a single quote to start the next, the comma before starting the next quote for the second user and closing it as well via '''', then the value of the user again, and finally closing the second user with close quote ''''. Finally adding a comma and getdate() calls. Yes, stupid tricky in the quoting.
An easier implementation without CONCAT() is just using + between each explicit part such as
select '''' + #User + '''' + ', ' + '''' + #User + '''' + ', Getdate(), getdate()' ;
where each '''' is a single quote thus resulting in
' + Bob + ' + , + ' + Bob + ' + , Getdate(), getdate()
resulting in
'Bob', 'Bob', Getdate(), getdate()
I'll leave the final UpdateColumns to you to confirm your intended output.
But, as mentioned, beware of possible SQL injection when you are dynamically building SQL statements with embedded parameter values as this appears to be doing.
Here is another way to approach this:
Declare #FileKey varchar(10) = 's_3'
, #TargetColNames nvarchar(max) = ''
, #SourceColNames nvarchar(max) = ''
, #SourceColNamesInsert nvarchar(max) = ''
, #UpdateColumns nvarchar(max) = '';
Set #TargetColNames = concat_ws(', ', '[CreatedUser]', '[UpdatedUser]', '[CreatedDateTime]', '[UpdatedDateTime]');
If #FileKey In ('s_1', 's_2')
Set #TargetColNames = concat_ws(', ', #TargetColNames, '[UpdatedDateTime]', '[IsDeleted]', '[DeletedOn]');
Print #TargetColNames;
Set #SourceColNames = concat_ws(', ', '[CreatedUser]', '[UpdatedUser]', '[CreatedDateTime]', '[UpdatedDateTime]');
Set #SourceColNamesInsert = concat_ws(', ', quotename('#User', char(39)), quotename('Getdate()', char(39)), quotename('Getdate()', char(39)));
Print #SourceColNames;
Print #SourceColNamesInsert;
I have the following statement, where I'm passing in a parameter like this:
'0001,0003'
I was following the REPLACE answer from this question:
SQL IN Statement splitting parameter
But I'm trying to take it out of dynamic sql. My returned result is NULL. Is there anyway to get this to work?
DECLARE #partialLNum varchar(MAX)
DECLARE #lNumConCat varchar(500)
DECLARE #tTemp table(lNum varchar(15))
DECLARE #formatIN varchar(MAX)
set #partialLNum = '0001,0003'
set #formatIN = ''''+ REPLACE(#partialLNum,',',''',''')+''''
insert into #tTemp
select substring(lNum,1,2) + '-' + substring(lNum,3,3) + '-' + substring(lNum,6,2) + '-' + substring(lNum,8,3)
from [rpt].[myView]
where LNum IN (#formatIN)
select #lNumConCat = COALESCE(#lNumConCat +'' , '', '''') + LNum from #tTemp
select #lNumConCat
in takes a list of values. So:
where LNum IN ('0001,0003')
has a list with one element, that happens to have a comment in it.
One way to do what you want is using like:
where ',' + partialLNum + ',' like '%,' + LNum + ',%'
There should suffice, but there are other ways using a split() function as well.
I have a dynamic procedure where an input variable can either be a date with the corresponding column being formatted as datetime OR a string with the corresponding columns being formatted as nvarchar.
If the input is a date then this would look like yyyy-mm-dd .
To cover this I tried to add the following to my Where clause but this creates the below error (if I remove this line then the rest of the procedure works as intended):
#searchTerm nvarchar(256) = ''
-- ...
WHERE CASE WHEN ''' + #searchCategory + ''' <> ''dateX'' THEN
(A.' + #searchCategory + ' LIKE ''%' + #searchTerm + '%'')
ELSE
(A.dateX = ''' + CAST(#searchTerm AS DATETIME) + ''')
END
-- ...
Error:
Conversion failed when converting date and/or time from character string.
Can someone tell me what I have to change here to make this work ?
Many thanks in advance, Mike.
You can't put a datetime value into a string. First cast as datetime to get it into the format you want then cast to a Varchar so it can be part of your dynamic string.
(A.dateX = ''' + CAST(CAST(#searchTerm AS DATETIME) AS VARCHAR(20)) + ''')
Or if #searchTerm is already in the format you want then you don't need to cast it
(A.dateX = #searchTerm)
Currently, I have a function to get list of columns of 1 table with detail attribute. And off course, there are some tables with a lot of columns. So, the output will be over 10.000 characters.
Here I test like this:
declare #aa nvarchar(max)
set #aa = dbo.fnGetColumnList('Table_Name')
print #aa
The result always has around 4000 characters. It looks like the SQL has truncated it.
What I know that when we declare nvarchar(max), SQL will supports up to 2^32-1 (2GB) for this string. But why it just has around 4000 characters?
When I execute like this:
select dbo.fnGetColumnList('Table_Name')
the result is correct.
And here is the code for the function:
-- get column list from table Mapping
ALTER FUNCTION [dbo].[fnGetColumnList] ( #tblName varchar (30))
RETURNS nvarchar(max)
AS
BEGIN
Declare #sql nvarchar(max)
set #sql = ''
SELECT #sql = #sql + case
when CHARINDEX('char', LOWER([DBType])) > 0 then ', ['+[DBColumn]+']' + ' ['+[DBType]+']' + ' ('+convert(varchar(10),[Length])+') NULL' + CHAR(13)
when CHARINDEX('char', LOWER([DBType])) > 0 then ', ['+[DBColumn]+']' + ' ['+[DBType]+']' + ' NULL' + CHAR(13)
ELSE ', ['+[DBColumn]+']' + ' ['+[DBType]+']' + ' NULL' + CHAR(13)
end FROM dbo.Mapping WHERE [DBTable] = #tblName
return #sql
END
Please advance.
This is almost always a variable assignment type problem, as explained in:
For Nvarchar(Max) I am only getting 4000 characters in TSQL?
If it's not that, then it's probably just the settings of Print to display too few characters:
nvarchar(max) still being truncated
Having looked at the updated code, it seems like it's the second issue, your print is truncating as it's not set to show enough characters.
You should see this by running
SELECT LEN(#aa)
You'll get a number larger than 4000, showing the value is held correctly in the variable.
As explained in Microsoft's nvar and nvarchar docs:
A common misconception is to think that with nchar(n) and nvarchar(n), the n defines the number of characters. However, in nchar(n) and nvarchar(n), the n defines the string length in byte-pairs (0-4,000). n never defines numbers of characters that can be stored. This is similar to the definition of char(n) and varchar(n).
There is an option in SQL Management Studio:
Tools > Options... > Query Results > SQL Server > Results to Text > Maximum number of characters displayed in each column
Hello Im using SQL2000 so I build a Dynamic Query and in the last case I have this :
IF (#apepac is not null and #nompac is not null and #month is not null )
SELECT #DynaSQL_1= #DynaSQL_1 + ' AND PACIENTE.apellidos like ''' + #apepac + '%'''+
' AND PACIENTE.nombres like ''' + #nompac + '%'''+
' AND DATENAME(MONTH,honorariotecnologo.fechaestudio) = ''' + #month +'''' +
' AND YEAR(honorariotecnologo.fechaestudio) = '+#year+''
so the parameter #year is declared in this way :
DECLARE #year int,
and the error I get from SQL output is :
Msg 245, Level 16, State 1, Line syntax
43Error to convert the nvarchar value '
What could be wrong?
Thanks!
By the way, Why if the parameter is declared as INT, on the body query it must have to be casted / converted? ...
You have to cast or convert the INT to a NVARCHAR. Google CAST CONVERT TSQL.
You need to cast your #Year as a character value.
Try this:
' AND YEAR(honorariotecnologo.fechaestudio) = ' + CAST(#year AS varchar(10))
You want this to take care of the conversion error...
' AND YEAR(honorariotecnologo.fechaestudio) = '+CAST(#year AS VARCHAR)
You want this if you want to add the single quote to the end of your string.
' AND YEAR(honorariotecnologo.fechaestudio) = '+CAST(#year AS VARCHAR) + ''''