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
 Dynamic SQL - Help

Author  Topic 

nirene
Yak Posting Veteran

98 Posts

Posted - 2010-06-05 : 01:08:04
Hai All,

Is this possible in SQL Server 2000

Select @Var=Field from Database.dbo.Table Where X=@Y

Can the same thing be done using Dynamic SQL

@SQLStr=’ Select @Var=Field from ‘ + @DBName +’.dbo.Table Where X=’’’ + @Y +’’’’

Exec sp_executesql @SQLStr

Print @Var

Nirene

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2010-06-05 : 01:35:34
You can do it with sp_executesql, but you have to return the value in @Var as an output parameter.

Also, you should pass the selection parameter, @Y, as an input parameter to sp_executesql to avoid possible SQL injection.

You should read about sp_executesql in SQL Server Books Online to see exactly how this is done.




CODO ERGO SUM
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-06-07 : 03:03:54
Make sure you read this fully
www.sommarksog.se/dynamic_sql.html

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -