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
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Storing/executing SQL statements in variables

Author  Topic 

Rangi
Starting Member

18 Posts

Posted - 2002-12-05 : 05:44:54
Is it possible in SQL Server 2000 to store then execute sql statements in variables?

For example, in pseudo-code:

DECLARE @sql AS sql
@sql = "SELECT * FROM myTable"
EXECUTE @sql

I know that this code above does not work but I am hoping you will be able to see what I am trying to do.

If I could do something like this then I would be able to generate sql statements dynamically in a stored procedure then execute them when they are ready.

Any help much appreciated,

Rangi

harshal_in
Aged Yak Warrior

633 Posts

Posted - 2002-12-05 : 06:18:56

Yes u can very well store sql statements in varables
DECLARE @sql as varchar(500)
@sql='select * from mytable'
sp_executesql @sql

this works fine.
u can find many articles in this site regarding dynamic sql

harshal




Edited by - harshal_in on 12/05/2002 06:19:44

Edited by - harshal_in on 12/05/2002 06:20:19
Go to Top of Page

AndrewMurphy
Master Smack Fu Yak Hacker

2916 Posts

Posted - 2002-12-05 : 06:22:42
It actually IS possible that style of code.....it's called (surprisingly) the DYNAMIC SQL technique.....search here for (many) examples of same.

Go to Top of Page

Rangi
Starting Member

18 Posts

Posted - 2002-12-05 : 06:26:34
Thank you both for your very helpful suggestions, just what I was looking for. I will take your advise and search for dynamic sql articles on this site.

Thanks,

Rangi

Go to Top of Page
   

- Advertisement -