concatenate datetime with string - sql

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

Related

Conversion of DateTime

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;

How to extract a value from Dynamic SQL result?

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.

Comma seperated values to SQL IN STATEMENT

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

sql dates as column name

I want a table with columns named after dates.
example:
SELECT * AS GETDATE() FROM mytable;
From what I've read on the internet, it looks as though I will need to use dynamic SQL (?) something in the lines of this:
DECLARE #dt smalldatetime
SET #dt = GETDATE()
DECLARE #str varchar(100)
SET #str = 'SELECT * AS ' + convert(varchar(100), GETDATE(), 120) + ' FROM mytable'
EXEC(#str);
But this doesn't work. says "incorrect syntax near the keyword 'AS'
All I had to do was change from SELECT * to SELECT [the thing i needed]
DECLARE #dt smalldatetime
SET #dt = GETDATE()
DECLARE #str varchar(100)
SET #str = 'SELECT Item AS ' + convert(varchar(100), GETDATE(), 120) + ' FROM mytable'
EXEC(#str);
this works.
Try this:
DECLARE #dt smalldatetime
SET #dt = GETDATE()
DECLARE #str varchar(100)
SET #str = 'SELECT Item AS '+'''' + convert(varchar(100), GETDATE(), 120) +'''' + ' FROM mytable'
EXEC(#str);

How do I name a column as a date value

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