2

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'
0

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

@sanmah, you also need the quotes suggested by the answer to get the correct results don't you?
@ala, when i concatenate where with cast() statement, it worked fine without quotes...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.