Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 String Concatenation in Stored proc

Author  Topic 

pkanuri
Starting Member

1 Post

Posted - 2009-06-12 : 05:29:14
I'm writing my first Stored Procedure where I'd be building a SQL Query using String Concatenation. This is required since I need to insert parameters in between.
I'm at a loss to understand why the following code doesn't work.
The StartTime is a column in GSMCallTrace Table.

*****************BEGIN************************
declare @stmt varchar(255)

select @stmt = 'select ' + 'datediff(day' + "GSMCallTrace.StartTime" + ',GetDate())' + ' from GSMCallTrace '

select @stmt from GSMCallTrace

******************END*************************

This of course works
Select datediff(day,StartTime,GetDate()) from GSMCallTrace

But why doesn't the constructed/concatenated string query above throw an error.
Can I get it to work?

Please help.

Thanks,
Phani

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2009-06-12 : 05:48:16
There is no comma between DAY and first parameter in DATEDIFF function.

ALWAYS, always, print the @stmt variable when it doesn't work for you.
You can copy the putput from the print to a new query window and run it there to get the details of the error message!



E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2009-06-12 : 05:49:25
quote:
Originally posted by pkanuri

declare @stmt varchar(255)

select @stmt = 'select ' + 'datediff(day' + "GSMCallTrace.StartTime" + ',GetDate())' + ' from GSMCallTrace '

select @stmt from GSMCallTrace
Why are you even considering dynamic sql for this query?



E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-06-14 : 01:52:14
there's no need to use dynamic sql here unless you're learning to use it
Go to Top of Page
   

- Advertisement -