I'm trying to get a few values from a dynamic SELECT
This is my code:
DECLARE #sqlCommand varchar(1000)
DECLARE #colName varchar(20)
DECLARE #tableName varchar(20)
DECLARE #myNum int
DECLARE #varDate varchar(19)
DECLARE #myTime datetime2
set #varDate = getdate()
SET #colName = 'col1'
SET #tableName = 'table'
SET #sqlCommand = 'SELECT top 1 #myTime=mytime, #myNum=' + #colName + ' FROM ' + #tableName + ' WHERE mytime>=''' + #varDate + ''' ORDER BY mytime'
PRINT #sqlCommand
EXEC(#sqlCommand)
When I print the SQL command, this is what I get:
SELECT top 1 #myTime=mytime, #myNum=col1
FROM table
WHERE mytime>='Jul 25 2017 4:40PM'
ORDER BY mytime
When I try to EXEC it, I get this error:
Must declare the scalar variable "#myTime".
If I do this:
SET #sqlCommand = 'SELECT top 1 mytime, ' + #colName + ' FROM ' + #tableName + ' WHERE mytime>=''' + #varDate + ''' ORDER BY mytime'
It works well, but I need to use that data.
Thanks in advance.
Use sp_executesql:
exec sp_executesql #sqlCommand,
N'#myNum int output, #myTime datetime2 output, #vardate datetime2',
#myNum = #myNum output,
#myTime = #myTime output,
#vardate = #vardate;
This is a much better way to run SQL code, because handling parameters is built-in.
Simple...use the Variable passing features, make to identify the Output variables last in the list of variables
Rough signature but should get you started #o_sdate, #o_edate, and #o_resp are variables declared outside of the dynamic sql
exec sp_executesql #sql
, N'#sdate date, #edate date, #resp smallint OUTPUT'
, #sdate = #o_sdate, #edate = #o_edate, #resp = #o_resp OUTPUT
You should use "insert exec" to get your variable out off the dynamic sql. Or use a "double-hash"-table.
DECLARE #sqlCommand varchar(1000)
DECLARE #colName varchar(20)
DECLARE #tableName varchar(20)
DECLARE #myNum int
DECLARE #varDate varchar(19)
DECLARE #myTime datetime2
set #varDate = getdate()
SET #colName = 'col1'
SET #tableName = 'table'
SET #sqlCommand = 'SELECT top 1 mytime, ' + #colName + ' FROM ' + #tableName + ' WHERE mytime>=''' + #varDate + ''' ORDER BY mytime'
PRINT #sqlCommand
create table #t1 (mytime datetime, col1 varchar(20))
insert #t1 (mytime, col1) EXEC(#sqlCommand)
select #mytime=mytime, #col1=col1 from #t1
I hope you got the idea.
Related
I am trying to execute some logic on a remote server using dynamic SQL, but when I set the dynamic SQL and try to call it nothing happens.. If I call the execution without making the execution dynamic it works without issue.
Not sure if what I am trying to do is allowed when passing OUTPUT values but figured I would see if anyone has any thoughts
DECLARE #sqlserver NVARCHAR(MAX) = ''
DECLARE #DBName NVARCHAR(MAX) = ''
DECLARE #parms NVARCHAR(MAX) = N'#output INT OUT', #output INT, #sql NVARCHAR(MAX) = '
;WITH DuplicateStatusCodes AS (
SELECT CodeTypeID FROM EDDSDBO.Code WHERE Name = ''Master'' OR Name = ''Unique'' OR Name = ''Duplicate''
)
SELECT ROW_NUMBER() OVER (ORDER BY CodeTypeID) RN, CodeTypeID INTO #temp
FROM DuplicateStatusCodes
GROUP BY CodeTypeID
HAVING COUNT(CodeTypeID) = 3
DECLARE #count INT = (SELECT COUNT(1) FROM #temp)
DECLARE #ctr INT = 1;
IF #count > 0
BEGIN
WHILE #ctr <= #count BEGIN
DECLARE #parms NVARCHAR(MAX) = N''#inneroutput INT OUT'';
DECLARE #inneroutput INT
DECLARE #codeartifact INT = (SELECT CodeTypeID FROM #temp WHERE RN <= 1 * #ctr and RN > 1 * (#ctr - 1))
DECLARE #duplicatestatuscheck NVARCHAR(MAX) = ''SELECT #inneroutput = COUNT(1) FROM eddsdbo.codeartifact_''+CAST(#codeartifact AS VARCHAR)+''''
EXEC sys.sp_executesql #duplicatestatuscheck, #parms, #inneroutput OUT
SELECT #output = #inneroutput
IF #inneroutput > 0
BREAK;
SET #ctr = #ctr + 1;
END
END
ELSE
BEGIN
SELECT #output = ''0''
END
'
DECLARE #linksql NVARCHAR(MAX) = '
DECLARE #sql NVARCHAR(MAX)
DECLARE #parms NVARCHAR(MAX) = N''#output INT OUT''
EXEC '+QUOTENAME(#sqlserver)+'.'+QUOTENAME(#DBName)+'.sys.sp_executesql #sql, #parms, #output = #output OUT'
--This does not work
EXEC sp_executesql #linksql, #parms, #output = #output
PRINT #output
--This works fine
EXEC [RemoteServerName].[DatabaseName].sys.sp_executesql #sql, #parms, #output = #output OUT ```
Appreciate any help
you would need to use OPENROWSET. Something like this:
DECLARE #ServerName VARCHAR(255) = '...'
,#DatabaseName VARCHAR(255) = '...'
,#Pwd VARCHAR(255) = '...'
,#UID VARCHAR(255) = '...'
,#Name VARCHAR(255) = 'Master'
DECLARE #connect varchar(max) = '''Server=' + #ServerName + ';database=' + #DatabaseName + ';Uid=' + #UID + ';Pwd=' + #Pwd + ';'''
declare #sqlstring varchar(max) = 'SET ANSI_NULLS OFF; SET ANSI_WARNINGS OFF;
SELECT CodeTypeID FROM EDDSDBO.Code WHERE Name = ''''' + #Name + ''''' '
declare #TheExecutableStr varchar(max) = '
SELECT *
FROM OPENROWSET(''SQLNCLI'', ' + #connect + ',
''' + #sqlstring + ''')'
SELECT #TheExecutableStr
--EXEC(#TheExecutableStr)
Please note you have to count single quote very diligently, hence SELECT #TheExecutableStr. It is for debugging purposes. You can view the query to be executed and actually copy/paste and execute before uncommenting last statement.
Hope it helps.
just noticed, you have sys.sp_executesql within sys.sp_executesql which might be problematic. you might need to find a way to refactor the code.
declare #sql as nvarchar(500)=''
set #sql='
declare #N4 as int = 1
declare #ms as nvarchar(100) = concat(''ms'', convert(nvarchar(10), #N4))
select #ms
'
exec #sql
I want output as ms1.
DECLARE #SQL AS NVARCHAR(500)=''
SET #sql='
while (#i <10)
begin
PRINT (''MS_''+#I)
set #i=#i+1
end
'
EXEC(#SQL)
not generating value for #i
i want to put this code in while loop as I want to access ms1 to ms10
Use sp_executesql which supports ouput params
DECLARE #MS VARCHAR(50)
exec sp_executesql N'declare #N4 as int = 1;
SELECT #MS= concat(''ms'', convert(nvarchar(10), #N4))',
N'#MS VARCHAR(50) output', #MS output;
SELECT #MS
Yes, you can use and for that you need to use sp_executesql like this -
Declare #sql as nvarchar(500)='', #Params NVARCHAR(500),
#N4 Int = 1, #ms nvarchar(100)
SET #Params = '#N4 Int, #ms nvarchar(100) OUTPUT'
set #sql= N'SELECT #ms = concat(''ms'', convert(nvarchar(10), #N4))'
EXEC SP_EXECUTESQL #sql, #Params, #N4 = #N4, #ms = #ms OUTPUT
SELECT #ms
Use While statement and string concatenation to get your result :
DECLARE #StartValue INT = 1
DECLARE #EndValue INT = 10
DECLARE #Query VARCHAR(500) = ''
WHILE #StartValue < #EndValue
BEGIN
SET #Query = #Query + 'sms_' + CAST(#StartValue AS VARCHAR) + ','
SET #StartValue = #StartValue + 1
END
SELECT Query
i am getting an error when trying to concatenate date and string.
declare #select varchar(max)
declare #where varchar(max)
set #select = 'select * from tbl Emp........'
#where = ' where Emp.date >='+ cast((cast(getdate() as date)) as varchar(20))
exec(#select+#where)
I also tried to do like below but didn't work:
declare #today varchar(20)
#today = cast((cast(getdate() as date))
#where = 'where Emp.date> =' + '#today'
Try something like this...
declare #select varchar(max)
declare #where varchar(max)
set #select = 'select * from tbl Emp '
set #where = ' where Emp.date >= ''' + CONVERT(varchar(8),getdate(),112) + ''''
exec(#select+#where)
Or an even better option would be something like this.....
DECLARE #Sql nvarchar(max);
DECLARE #Date DATE = GETDATE();
SET #Sql = N' select * from tbl Emp '
+ N' where Emp.date >= #Date'
Exec sp_executesql #Sql
,N'#Date DATE'
,#Date
But why do you even need dynamic sql for this simple query why cant you simply do
DECLARE #Date DATE = GETDATE();
select * from tbl Emp
where Emp.date >= #Date
I have the following stored procedure:
ALTER proc [dbo].[insertperoll] #name nvarchar(50) , #snum int , #gnum int
as
DECLARE #value nvarchar(10)
SET #value = 's'+CONVERT(nvarchar(50),#snum)
DECLARE #sqlText nvarchar(1000);
DECLARE #sqlText2 nvarchar(1000);
DECLARE #sqlText3 nvarchar(1000);
declare #g nvarchar(50) = '''g1'''
SET #sqlText = N'SELECT ' + #value + N' FROM dbo.GrideBtable'
SET #sqlText2 = ' where Gnumber = '+#g --here is the problem it error invalid column name -- the #g is value from the table condition
set #sqlText3 = #sqlText+#sqlText2
Exec (#sqlText3) -- here how can i save the result of the exec into varibale
declare #sal nvarchar(50) = #sqlText3
insert employ (name,Snumber,Gnumber,Salary) values(#name,#snum,#gnum,#sal)
QUESTION: How to put in condition variable gets value from the table when i exec it it think that the #g is column but its not its a value from the table to test it so i display one value after the exec the other QUESTION is how to save the result from the exec in variable and then use that value
I'm using SQL Server 2008 (9.0 RTM)
This will be a stored procedure
Thanks in advance
Not sure why you would go through all the loops to insert into the table where you can have a simple insert query like ..
ALTER PROC dbo.[insertperoll] #name nvarchar(50) , #snum int , #gnum int
AS
insert employ (name, Snumber, Gnumber, Salary)
select #name
, #sum
, #gnum
, case when #snum = 1 then s1
when #snum = 2 then s2
when #snum = 3 then s3
when #snum = 4 then s4
end as Salary
from dbo.GrideBtable
where Gnumber = #gnum
If your intent is to have the proc retrieve a salary value from a column determined from the parameter snum and then make an insert into employ using the values passed as parameters and the salary retrieved I think you could refactor your procedure to this:
CREATE proc [dbo].[insertperoll] #name nvarchar(50) , #snum int , #gnum int AS
DECLARE #g NVARCHAR(50) = 'g1'
DECLARE #sql NVARCHAR(MAX);
SET #sql = N'INSERT employ (name,Snumber,Gnumber,Salary) '
SET #sql += N'SELECT ' + QUOTENAME(#name, '''')
SET #sql += N', ' + CAST(#snum AS NVARCHAR(50))
SET #sql += N', ' + CAST(#gnum AS NVARCHAR(50))
SET #sql += N', s' + CAST(#snum AS NVARCHAR(50))
SET #sql += N' FROM dbo.GrideBtable'
SET #sql += N' WHERE Gnumber = ' + QUOTENAME(#g, '''')
EXEC (#sql)
Of course you could add the #g variable to the procedure parameters instead of having it hard coded in the procedure and call it as:
EXEC insertperoll #name='john', #snum=10, #gnum=100, #g='g1'
Sample SQL Fiddle (with some assumptions made about table structure)
You could do this using sp_executesql instead of exec() since this will allow you to use parameters, you can use an output parameter to get the value from the query:
DECLARE #SQL NVARCHAR(MAX) = N'SELECT #val = ' + CONVERT(NVARCHAR(10),#snum) +
N' FROM dbo.GrideBtable WHERE Gnumber = #G1';
DECLARE #val INT; -- NOT SURE OF DATATYPE REQUIRED
EXECUTE sp_executesql #SQL, N'#G1 VARCHAR(20), #val INT OUT', 'G1', #val OUT;
I am trying to search within the values (table names) returned from a query to check if there is a record and some values in that record are null. If they are, then I want to insert the table's name to a temporary table. I get an error:
Conversion failed when converting the varchar value 'count(*)
FROM step_inusd_20130618 WHERE jobDateClosed IS NULL' to data type int.
This is the query:
DECLARE #table_name VARCHAR(150)
DECLARE #sql VARCHAR(1000)
DECLARE #test int
SELECT #table_name = tableName FROM #temp WHERE id = #count
SET #sql = 'SELECT * FROM ' + #table_name + ' WHERE jobDateClosed IS NULL'
--ERROR is below:
select #test = 'count(*) FROM ' + #table_name + ' WHERE jobDateClosed IS NULL'
--PRINT #sql
-- EXEC(#sql)
IF #test > 0
BEGIN
INSERT INTO #temp2 (tablename) VALUES ( #table_name);
END
SET #count = #count + 1
Any ideas how to convert the result of the count into an integer?
Check for sp_executesql where you may define output parameters.
DECLARE #table_name VARCHAR(150)
DECLARE #sql VARCHAR(1000)
DECLARE #test int
SELECT #table_name = tableName FROM #temp WHERE id = #count
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
SET #SQLString = N'SELECT #test = count(*) FROM ' + #table_name + ' WHERE jobDateClosed IS NULL'
SET #ParmDefinition = N'#test int OUTPUT';
EXECUTE sp_executesql #SQLString, #ParmDefinition, #test=#test OUTPUT;
IF #test > 0
BEGIN
INSERT INTO #temp2 (tablename) VALUES ( #table_name);
END
SET #count = #count + 1
Shouldn't be "SET" instead of "select" ?
E.g., changing:
select #test = 'count(*) FROM ' + #table_name + ' WHERE jobDateClosed IS NULL'
for:
SET #test = 'select count(*) FROM ' + #table_name + ' WHERE jobDateClosed IS NULL'
As I see, your problem is, that $test variable is INT and you are trying to assign to it the TEXT value 'count ...'
Use aproach like:
SELECT somevalue INTO myvar FROM mytable WHERE uid=1;
I trimmed out the stuff not needed to show how to do this, so here it is:
DECLARE #table_name VARCHAR(150)
DECLARE #CountStatement NVARCHAR(1000)
DECLARE #test int
SELECT #table_name = tableName FROM #temp WHERE id = #count
SET #CountStatement = 'select #test = count(*) FROM ' + #table_name + ' WHERE jobDateClosed IS NULL'
EXECUTE sp_executesql #CountStatement, N'#test INT OUTPUT', #test OUTPUT;
SELECT #test