Not SET variable #Set. This return null or SQL return error.
declare #Field as varchar(10);
declare #Set as varchar(10);
set #Field = 'id_fonte'
declare #sql nvarchar(max)
set #sql = 'select ' + #Set + ' = id_fonte
from fontes
where [' + replace(#Field, '''', '''''') + '] = 54';
exec sp_executesql #sql
You have multiple issues here. First, the variable #set has not been given a value, therefore it is NULL. Anytime you use the + operator to do string concatenation, any string + NULL will equal NULL. Thus your #sql variable will be set to NULL. You can see this by changing one your lines as follows:
declare #Set as varchar(10) = '';
Nevertheless, the syntax of the statement stored in the #sql command looks suspect. Add the line
PRINT #sql
before the execution during testing to see the exact syntax of the command that you are executing.
You can use an OUTPUT parameter with sp_executesql, like this:
Note correct use of QUOTENAME to escape the column name.
declare #Field as varchar(10) = 'id_fonte';
declare #Set as varchar(10);
declare #sql nvarchar(max) = '
select #Set = id_fonte
from fontes
where ' + QUOTENAME(#Field) + ' = 54;
';
print #sql; -- for testing
exec sp_executesql
#sql,
N'#Set varchar(10) OUTPUT',
#Set = #Set OUTPUT;
Related
I have a query like this:
DECLARE #TaskId UNIQUEIDENTIFIER
DECLARE #TaskName VARCHAR(255) = 'MasterSet'
DECLARE #sql NVARCHAR(MAX)
DECLARE #StartingDateTask DATETIME2 = (SELECT TOP 1 [Date]
FROM [TaskStatusAudit]
WHERE [TaskId] = 'A1FDFC16-904D-4560-B19D-5E7D4FEB1C2B'
AND [TaskStatusName] = 'IN-PROGRESS')
DECLARE #EndingDateTask DATETIME2 = (SELECT TOP 1 [Date]
FROM [TaskStatusAudit]
WHERE [TaskId] = 'A1FDFC16-904D-4560-B19D-5E7D4FEB1C2B'
AND [TaskStatusName] = 'COMPLETED')
SET #sql = N'SELECT dbo.TotalMinuteRange(#StartingDateTask,#EndingDateTask) as ' + quotename(#TaskName) + N''
EXEC sp_executesql #sql
Problem is when I execute it I get this error:
Must declare the scalar variable "#StartingDateTask".
Any ideas why I getting that if I declare my variable correctly? Regards
When executing sp_executesql you need to declare and pass the variables to sp_executesql something like..
SET #sql = N'SELECT dbo.TotalMinuteRange(#StartingDateTask,#EndingDateTask) as '
+ quotename(#TaskName) + N''
exec sp_executesql #sql
, N'#StartingDateTask DATETIME2 , #EndingDateTask DATETIME2'
, #StartingDateTask
, #EndingDateTask
Second parameter is the variable declaration parameter followed by the actual variables separately.
You can also do like taking a parameters variable and assign it.
declare #params nvarchar(100)
set #params='#StartingDateTask DATETIME2,#EndingDateTask DATETIME2'
SET #sql = N'SELECT dbo.TotalMinuteRange(#StartingDateTask,#EndingDateTask) as '
+ quotename(#TaskName) + N''
exec sp_executesql #sql
, #params
, #StartingDateTask
, #EndingDateTask
I am getting an error running the code below. I believe it as to do with the number of single quotes used.
How can I set a variable inside OPENQUERY command?
#declare #myStr varchar(6)
set #myStr = 'Test1'
SELECT *
FROM OPENQUERY("192.168.1.1",'SET FMTONLY OFF; EXEC spNewTest #Param1 = ''+ #myStr +''')
Click to see the error message
Regards,
Elio Fernandes
If you want to create a single quote within a string you have to put in two single quotes. For example:
'''this is a string''' would be a string containing the following:
'this is a string'
So for your problem, you have to change your code to this:
#declare #myStr varchar(6)
set #myStr = 'Test1'
SELECT *
FROM OPENQUERY("192.168.1.1",'SET FMTONLY OFF; EXEC spNewTest #Param1 = '''+ #myStr +'''')
I just found the answer for my question, so I thought sharing it with you.
DECLARE #QUERY VARCHAR(MAX)
DECLARE #TSQL VARCHAR(100)
DECLARE #SP VARCHAR(50)
DECLARE #PARAMETERS VARCHAR(MAX)
DECLARE #PARAM1 VARCHAR(50)
DECLARE #PARAM2 VARCHAR(50)
SET #TSQL = N'SELECT * FROM OPENQUERY([192.168.1.1], ''SET FMTONLY OFF; '
SET #SP = 'EXEC spNewTest '
SET #PARAM1 = '#Type='''+ QUOTENAME('Test','''') + ''''
SET #PARAM2 = '#Year='''+ QUOTENAME('2016','''') + ''''
SET #PARAMETERS = #PARAM1 + ', ' + #PARAM2
SET #QUERY = #TSQL + #SP + #PARAMETERS + ''')'
EXECUTE (#QUERY)
Thanks
How to set value to declared variable in SQL Server.
DECLARE #V_SEQUENCE INT, #V_SEQUENCENAME NVARCHAR(MAX);
SET #V_SEQUENCENAME = 'dbo.MYSEQ';
EXEC('SELECT #V_SEQUENCE = NEXT VALUE FOR ' + #V_SEQUENCENAME)
SELECT #V_SEQUENCE
Here i am getting an error:
Must declare the scalar variable "#V_SEQUENCE"'
Please tell me how to get result of #V_SEQUENCE.
You want to pass a value out of the execute. I recommend that you use sp_executesql:
DECLARE #V_SEQUENCE INT, #V_SEQUENCENAME NVARCHAR(MAX), #SQL NVARCHAR(MAX);
SET #V_SEQUENCENAME = 'dbo.MYSEQ';
SELECT #SQL = 'SELECT #V_SEQUENCE = NEXT VALUE FOR ' + #V_SEQUENCENAME;
EXEC sp_executesql #SQL, N'#V_SEQUENCE INT OUTPUT', #V_SEQUENCE = #V_SEQUENCE OUTPUT;
SELECT #V_SEQUENCE;
DECLARE #sql NVARCHAR(max)
DECLARE #ParmDefinition NVARCHAR(500)
SET #sql = 'UPDATE [Table1] SET [Table1].[#columnName] = TEST';
SET #ParmDefinition = N'#columnName NVARCHAR(50)';
EXEC sp_executesql #sql, #ParmDefinition, #columnName = N'MyColumn';
When I run the above query, I get Invalid column name '#columnName'.. Clearly, the column name is not being replaced when the query is run.
In reality, my #sql variable is much larger and I have many columns I wish to update, thus I would like to avoid doing SET SQL = for all enumerations of the column name.
I'd like to declare the sql string once, and invoke the query with different values. e.g.:
EXEC sp_executesql #sql, #ParmDefinition, #columnName = N'MyColumn';
EXEC sp_executesql #sql, #ParmDefinition, #columnName = N'AnotherColumn';
EXEC sp_executesql #sql, #ParmDefinition, #columnName = N'YetAnotherColumn';
-- And so on
Is something like this possible?
Yes, you have to concatenate the variable outside the string. In other words:
SET #sql = 'UPDATE [Table1] SET [Table1].[' + #columnName + '] = t1.Value ' +
EDIT: Another solution we have used is to replace tokens in the base sql to construct a new sql variable for execution.
DECLARE #sql nvarchar(max) = 'SELECT #ColumnName FROM #TableName';
DECLARE #sql2 nvarchar(max) = REPLACE(REPLACE(#sql,'#ColumnName',#ColumnNameVariable),'#TableName',#TableNameVariable)
EXEC (#sql2)
...Some code that changes the values of #ColumnNameVariable and #TableNameVariable...
DECLARE #sql2 nvarchar(max) = REPLACE(REPLACE(#sql,'#ColumnName',#ColumnNameVariable),'#TableName',#TableNameVariable)
EXEC (#sql2)
And you'll notice that the Declaration and Exec of SQL2 are exactly the same lines in both cases. This lends itself to use in a LOOP if that is applicable. (Except that you wouldn't DECLARE #Sql2 in the loop...just populate/re-populate it).
First of all, kudos for trying to parameterize your dsql using sp_executesql. The problem is, you can only parameterize something you could put into a variable in the first place such as in a search predicate or select list.
However it's still possible; just concatenate the column name with your DSQL string, wrapping it with the quotename function
set #sql = 'update table1 set table1.' + quotename(#ColumnName) + ' = ...
I need to get data from a table in a database who's database name will be determined as a variable during a trigger. I then, knowing this variable need to get a seqno from a table in the determined database for a item which was also determined as a variable during a trigger.
I am trying this route as I assume I need to build the SQL statement before I set it to a variable.
This is not working and I need to know the best way on how I can do this:
DECLARE #SU_SEQNO INTEGER, #SU_NAME VARCHAR(50), #SU_OWNER VARCHAR(15), #SUD_SEQNO INTEGER, #SQL NVARCHAR(500)
SET #SU_OWNER = 'XXX'
SET #SU_NAME = '1ABC234'
SET #SQL ='SELECT #SUD_SEQNO=SEQNO FROM ' + (#SU_OWNER) + '.SU_MAIN
WHERE UNITNAME= ' + #SU_NAME
SET #SUD_SEQNO = (EXECUTE (#SQL))
Thanks alot for any help with this
From: Get result from dynamic SQL in stored procedure
SET #SQL = N'SELECT DISTINCT #FiscalYear = FiscalYear FROM ' + #DataSource;
EXEC sp_executesql #SQL, N'#FiscalYear INT OUTPUT', #FiscalYear OUTPUT;
PRINT #FiscalYear;
I'd re-engineer to use the sp_executesql method as shown above. That should do the trick.
I have amended the code, and it works
declare #su_owner varchar(15) = 'DBTEST'
declare #SU_SEQNO INTEGER=1, #SUD_SEQNO INTEGER=0, #SQL NVARCHAR(500)
DECLARE #ParmDefinition NVARCHAR(500), #SU_NAME_INPUT VARCHAR(50)='SU123'
SET #SU_NAME_INPUT = (SELECT UNITNAME FROM SU_MAIN WHERE SEQNO=#SU_SEQNO)
SET #SU_NAME = (SELECT UNITNAME FROM SU_MAIN WHERE SEQNO=#SU_SEQNO)
SET #SQL = N'SELECT #sud_seqnoOUT=MAX(SEQNO) FROM ' + quotename(#su_owner) + '.[dbo].[SU_MAIN] WHERE UNITNAME]=#SU_NAME_INPUT' ;
SET #ParmDefinition = N'#SU_NAME_INPUT VARCHAR(50),#sud_seqnoOUT INT OUTPUT'
EXEC sp_executesql #SQL,#ParmDefinition,#SU_NAME_INPUT = #SU_NAME,
#sud_seqnoOUT = #SUD_SEQNO OUTPUT