Incorrect syntax near '=' in Exec statement - sql-server

when I execute this:
declare #INP_ITBL_NM_SQL char (64)
Exec('
select '+#INP_ITBL_NM_SQL+' =
concat(LTRIM(RTRIM(a.db_schema_name)),LTRIM(RTRIM(b.Name)))
from '+#db_and_schema+' as a, '+#split_itbl+' as b
where b.ID = 2 and a.libname = (select c.Name from
'+#split_itbl+' as c where c.ID = 1)
')
I get the following error:
Msg 102, Level 15, State 1, Line 2 Incorrect syntax near '='.
The variables inside the select statement are temporary tables which (need to) change their name every run.
Thanks for the help!

You are getting that error because you are trying to set the value of a local variable to a value from within dynamic SQL. So when you print out that SQL text it looks something like:
SELECT = concat…
You should do this using output parameters with sp_executesql. Something like the following:
DECLARE #SQL nvarchar(max)
DECLARE #ParamDef nvarchar(200)
DECLARE #INP_ITBL_NM_SQL varchar(100) = ''
SET #ParamDef = N'#INP_ITBL_NM_SQL_OUTPUT varchar(100) OUTPUT';
SET #SQL = N'select #INP_ITBL_NM_SQL_OUTPUT = concat(LTRIM(RTRIM(a.db_schema_name)),LTRIM(RTRIM(b.Name)))
from '+ #db_and_schema+ ' as a, ' + #split_itbl +' as b
where b.ID = 2 and a.libname = (select c.Name from
'+ #split_itbl +' as c where c.ID = 1)'
EXEC sp_executesql #SQL, #ParamDef, #INP_ITBL_NM_SQL_OUTPUT=#INP_ITBL_NM_SQL OUTPUT;
SELECT #INP_ITBL_NM_SQL

Related

T-SQL variable not used in sp_execsql

I am running a cursor that executes dynamic SQL using a variable.
SET #Wk = CAST(#Cntr AS nvarchar(5))
DECLARE #params nvarchar(30) = N'#Wk nvarchar(5)'
-- .. start cursor
EXEC sp_executesql N'ALTER TABLE #Temp DROP COLUMN [WK #WK Sold]', #params, #Wk
I get the error
Msg 4924, Level 16, State 1, Line 4
ALTER TABLE DROP COLUMN failed because column 'WK #WK Sold' does not exist in table #Temp
I know that #param and #Wk work because I ran
EXEC sp_executesql N'select #Wk', #params, #Wk
and it worked. I know I can just run
EXEC ('ALTER TABLE #Temp DROP COLUMN [WK ' + #Wk + ' Sold]')
but I'd like to use sp_executesql.
Is it even possible the way I have tried?
Thank you
The problem has nothing to do with the variable here. The problem is that you think that a variable/parameter when used in the context of an object results in that variable being injected into the statement. That doesn't happen. SELECT 1 AS [#a] return return a column aliased as literally #a not a column where the alias is the value of a variable called #a.
What you need to do here is safely inject the value into the dynamic statement and ideally validate the name too:
DECLARE #Cntr SomeDataType; --I don't know what the datatype should be.
DECLARE #wk nvarchar(5),
#Column sysname;
SET #wk = #Cntr; --No need for the cast here
SET #Column = (SELECT c.name
FROM tempdb.sys.tables t
JOIN tempdb.sys.columns c ON t.object_id = c.object_id
WHERE t.[name] LIKE N'#temp%'
AND c.name = N'WK
' + #wk + N' Sold');--Does your column name really have a carriage return and line break in it?
DECLARE #SQL nvarchar(MAX) = N'ALTER TABLE #Temp DROP COLUMN ' + QUOTENAME(#Column) + N';';
EXEC sys.sp_executesql #SQL;

Dynamic SQL Server Inner Join

I am building a dynamic sql query which loops on the columns that are available and perform and innerjoin to return the duplicates values.
So far looping in the column is working as a charm. The only issue is when I am building the dynamic inner join which is returning an error message. code is as below
DECLARE #Check VARCHAR(250) = 'Check_1'
DECLARE #SQLQUERY VARCHAR(MAX)
SET #SQLQUERY = 'SELECT A.PostingDate,A.DocumentNumber,A.Account,A.Reference,A.'+#Check+'
FROM TblDataTemp A
INNER JOIN TblDataHistory B
ON A.'+#Check +' = B.'+#Check +';'
EXEC #SQLQUERY
Msg 203, Level 16, State 2, Line 12
The name 'SELECT A.PostingDate,A.DocumentNumber,A.Account,A.Reference,A.Check_1
FROM TblDataTemp A
INNER JOIN TblDataHistory B
ON A.Check_1 = B.Check_1;' is not a valid identifier.
When using EXECUTE with dynamic SQL, you must use parentheses. Otherwise, SQL Server thinks the variable contains a procedure name.
DECLARE #Check VARCHAR(250) = 'Check_1'
DECLARE #SQLQUERY VARCHAR(MAX)
SET #SQLQUERY = 'SELECT A.PostingDate,A.DocumentNumber,A.Account,A.Reference,A.'+#Check+'
FROM TblDataTemp A
INNER JOIN TblDataHistory B
ON A.'+#Check +' = B.'+#Check +';'
EXEC (#SQLQUERY)

scope of the variable in dynamic SQL in SQL server

I got this dynamic code:
declare #TableName varchar(100)='Customer'
declare #DestinationcolumnList NVARCHAR(MAX)
DECLARE #ServerName NVARCHAR(100) = '----'
DECLARE #SourceDatabase NVARCHAR(100) = 'Staging'
DECLARE #DestinationDatabase NVARCHAR(100) = 'History'
declare #SQL NVARCHAR(MAX)
set #SQL='
select
'+#DestinationcolumnList+' = coalesce('+#DestinationcolumnList+', '''') +'',''+ char(13) + char(10) + quotename(cast(d.COLUMN_NAME as varchar(128)))
from ['+#ServerName+'].['+#DestinationDatabase+'].INFORMATION_SCHEMA.COLUMNS d
inner join ['+#ServerName+'].['+#SourceDatabase+'].INFORMATION_SCHEMA.COLUMNS s
on d.TABLE_NAME = s.TABLE_NAME
and s.COLUMN_NAME = d.COLUMN_NAME
where d.TABLE_NAME = '''+#TableName+'''
order by d.ORDINAL_POSITION
'
exec sp_executesql #SQL
select #DestinationcolumnList
its giving NULL value. when I execute same code without dynamic SQL its working fine. How scope of the variable works in dynamic SQL.
Thanks in advance.
In Dynamic SQL, variables declared outside the dynamic string are used to build a string, they are not used as a part of the string, so they cannot be used the way you are trying to do it: doing the undocumented trick of concatenating a variable with itself to produce a single string in a SELECT statement.
If you made the variable declaration part of the string, it should work:
set #SQL='
declare #DestinationcolumnList NVARCHAR(MAX);
select
#DestinationcolumnList = coalesce(#DestinationcolumnList, '''') +'',''+ char(13) + char(10) + quotename(cast(d.COLUMN_NAME as varchar(128)))
from ['+#ServerName+'].['+#DestinationDatabase+'].INFORMATION_SCHEMA.COLUMNS d
inner join ['+#ServerName+'].['+#SourceDatabase+'].INFORMATION_SCHEMA.COLUMNS s
on d.TABLE_NAME = s.TABLE_NAME
and s.COLUMN_NAME = d.COLUMN_NAME
where d.TABLE_NAME = '''+#TableName+'''
order by d.ORDINAL_POSITION;
select #DestinationcolumnList;
'
exec sp_executesql #SQL

How Insert the values of all the fields into a variable?

I really would appreciate your help for the following problem; I need to create a stored procedure, which accepts two parameters:
#TableName
#KeyField
I need to store them into 1 variable where the values are separated by |
For example the Customers table is as follows;
CustomerID CustomerName City
111 Adventure Boston
222 Pubs NY
And I execute EXEC mysp 'Customers', 111
I need to return the following result format:
#ReturnValue = 111|Adventure|Boston
Here is my stored proc;
CREATE PROCEDURE my sp
#table varchar
#key numeric
AS
#field varchar(40),
#object int
Select #object = object_id from systables where name =#table
--The instructions to create a cursor
WHILE (##FETCH_STATUS = 0 )
Select #object = name from sys.columns where object_id = #object
--The instructions to close and deallocate the cursor
--I have already to save the value using the EXEC command but is not working; something like
#String = Select #object from #table where CustomerID = #keyValue
Can you please help me,
Thanks
I agree with jesuraja that you will need the name of the key column as parameter ... if you can live with that you could try something like this ...
declare #tablename nvarchar(max) = 'Customers'
declare #keyfieldName nvarchar(max) = 'CustomerId'
declare #keyfieldValue int = 111
declare #sql nvarchar(max)
set #sql = convert(nvarchar(max),
(select (select 'isnull(convert(nvarchar(max), ' + c.name + '), '''') + '' | '' + ')
from sys.columns c join sys.tables t on c.object_id = t.object_id
where t.name = #tablename for xml path('')))
set #sql = 'SELECT ' + SUBSTRING(#sql, 1, len(#sql) - 9) + ' FROM ' + #tablename +
' WHERE ' + #keyfieldName + ' = #keyfieldValue'
exec sp_executesql #sql, N'#keyfieldValue as int', #keyfieldValue

declare variable in a table in SQL

I have a below query that requires help
Declare #DB varchar(3)
set #DB = 'C01'
SELECT * FROM SVBNORD+#DB WHERE ORDER_DATE = ''
But I get a message
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '+'.
Can you please help me correct my statement.
You should use execute to dynamically call the query:
Declare #DB varchar(3)
set #DB = 'C01'
execute ('SELECT * FROM SVBNORD'+#DB+' WHERE ORDER_DATE = '''' ')
You can't do this in normal sql. You can however build up sql dynamically and execute it, like so:
DECLARE #sql NVARCHAR(MAX);
SET #sql =
'SELECT * FROM SVBNORD' + #DB + N'WHERE ORDER_DATE = ''''';
EXEC(#sql);
You'll need to double up any single quotes in the query.

Resources