I have the following query:
set #DataEnd = '
select top 1 datetime
from IntradayHistory.dbo.IntradayDataHistory' + #product + '
where TickerID = ' + cast(#ticker as nvarchar(24)) + '
order by datetime desc
'
exec(#DateEnd)
This should return me only 1 value, and it did:
However, as I would need that value as a DateTime for dynamic query, how should I do it?
Using sp_executesql you can send an output parameter to your dynamic query.
DECLARE #sqlCommand NVARCHAR(MAX);
DECLARE #dateEnd DATETIME;
SET #sqlCommand = '
select top 1 #retVal = datetime
from IntradayHistory.dbo.IntradayDataHistory' + #product + '
where TickerID = ' + cast(#ticker as nvarchar(24)) + '
order by datetime desc
';
EXECUTE sp_executesql #sqlCommand, N'#retVal DATETIME OUTPUT', #retVal=#dateEnd OUTPUT;
SELECT #dateEnd;
Option B:
You can use temp table to store the result of dynamic query.
DECLARE #sqlCommand NVARCHAR(MAX);
SET #sqlCommand = '
select top 1 datetime
from IntradayHistory.dbo.IntradayDataHistory' + #product + '
where TickerID = ' + cast(#ticker as nvarchar(24)) + '
order by datetime desc
';
CREATE TABLE #temp1 (Result DATETIME);
INSERT INTO #temp1 EXEC (#sqlCommand);
SELECT * FROM #temp1;
Related
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.
If i have a comma separated list of values:
A1,B2,B3
How do i pass this into a variable and then form it into an SQL IN statement.
DECLARE #DATE AS VARCHAR(50)
SELECT #DATE = CONVERT(VARCHAR(8), Getdate(), 112)
--PRINT #DATE
DECLARE #TIME AS VARCHAR(50)
--PRINT TIME
SELECT #TIME = Replace(CONVERT(VARCHAR(5), Getdate(), 108), ':', '')
DECLARE #ID AS VARCHAR(50)
SELECT #ID = Replace(W0128001, 32322, 32323, 3232323, 2323232, ',', ',')
--PRINT #ID
DECLARE #QUERY NVARCHAR(MAX);
SET #QUERY = 'SELECT * INTO BACKUPTABLE_' + #DATE + #TIME
+ '
FROM TABLE
WHERE ID IN (' + '''' + #ID + ''')'
--EXEC #query
PRINT #QUERY
I have tried to do a replace above but i want it so that an end user can PASTE into the values and my script will take care of the commas and properly form it. It should also strip out the last commas from the end.
My output needs to read:
SELECT * INTO BACKUPTABLE_201606061503
FROM TABLE
WHERE ID IN ('W0128001','32322','32323','3232323','2323232')
For one thing, you don't surround it with single quotes:
SET #QUERY = 'SELECT * INTO BACKUPTABLE_' + #DATE + #TIME + '
FROM TABLE
WHERE ID IN (' + #ID + ')';
There are other ways to pass comma-delimited values to a SQL statement, including using a split() function or XML.
CREATE PROCEDURE [dbo].[CreateBackupTable]
#ID varchar(100) = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE #DATE VARCHAR(50)= CONVERT(VARCHAR(8), Getdate(), 112);
DECLARE #TIME VARCHAR(50) = Replace(CONVERT(VARCHAR(5), Getdate(), 108), ':', '')
declare #xml xml,#SQL NVARCHAR(MAX);
set #xml = N'<root><r>' + replace(#ID,',','</r><r>') + '</r></root>'
SET #SQL = N' SELECT * INTO ' + QUOTENAME('BACKUPTABLE_' + #DATE + #TIME)
+ N' from TableName '
+ N' where ID IN (
select r.value(''.'',''varchar(max)'') as item
from #xml.nodes(''//root/r'') as records(r)
)'
exec sp_executesql #sql
, N'#ID varchar(100), #xml XML'
, #ID
, #Xml
END
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 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
the results look like this but wher the column name says 'Today' I want it to be todays date.
Try this technique:
declare #dt datetime
declare #sql varchar(100)
set #dt = getdate()
set #sql = 'select 1 as [ ' + convert( varchar(25),#dt,120) + ']'
exec (#sql)
In your Case:
declare #dt datetime
declare #sql varchar(100)
set #dt = getdate()
set #sql = 'select 0 as [ ' + convert( varchar(25),#dt,120) + ']'
exec (#sql)
I would return an integer representing a day offset and parse it in the client, failing that you are going to have to use dynamic SQL or do something with the underlying column name itself;;
declare #sql nvarchar(128) = '
select
col1,
col2,
0 as [' + cast(getdate() as nvarchar(32)) + ']
from T'
exec(#sql)
Or
--today
declare #now varchar(32) = cast(getdate() as varchar(32))
--result to temp table
select col1, col2, 0 as [Now] into #T from TheTable
--rename col
exec tempdb..sp_rename '#T.Now', #now, 'COLUMN'
--select
select * from #T