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
 using variables in sql statements

Author  Topic 

CDNsqluser
Starting Member

2 Posts

Posted - 2010-12-23 : 22:08:03
Howdy

In the following SQL I am retrieving one field in one record and that field contains a very large string. To retrieve the record I need to supply a key [PuroLogKey] - in the example below I have tried to concatenate to bring in the variable as @Key but i get an error message.


DECLARE @Key varchar(10)
SET @Key = '71'
DECLARE @PuroMess varchar(8000)
EXEC sp_executesql N'SELECT @PuroMess = RetMess FROM mtxPurolatorLog WHERE PuroLogKey = ' + @Key, N'@PuroMess varchar(8000) output', @PuroMess output


If I hard code the variable like this it works perfect:


EXEC sp_executesql N'SELECT @PuroMess = RetMess FROM mtxPurolatorLog WHERE PuroLogKey = 71', N'@PuroMess varchar(8000) output', @PuroMess output


Any suggestions? I'm sure I'm overlooking the obvious...

Thanks-
JPR

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-12-23 : 22:38:04
Why are you using dynamic SQL for this? Why not just this:

SELECT @PuroMess = RetMess
FROM mtxPurolatorLog
WHERE PuroLogKey = @Key

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

CDNsqluser
Starting Member

2 Posts

Posted - 2010-12-23 : 22:48:02
You're right, simplicity is best and it works perfect.....thank you!

Jean-Paul
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-12-23 : 23:14:02
You're welcome, glad to help.

Dynamic SQL should be used very sparingly if at all.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -