Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL Server, how do I create a reference variable to a table?

I'm currently using sp_executesql to execute a T-SQL statement with a dynamic table name. However, it is really ugly to see something like:

set @sql = 'UPDATE '+Table_Name+' SET ... WHERE '+someVar+' = ... AND '+someVar2' = ...'
sp_executesql @sql

What I would rather like to have is a TABLE variable of which is a reference to a table, so I could do for example:

UPDATE TableRef SET ... WHERE ...

Because when I have really long T-SQL statements it gets really hard to read due to the format of it within a string.

Any suggestions would be helpful.

like image 442
Jón Trausti Avatar asked Jun 18 '10 10:06

Jón Trausti


1 Answers

Why don't you pass the parameters to sp_executeSQL instead?

http://msdn.microsoft.com/en-us/library/ms188001.aspx

I'd also have a read of this article too http://www.sommarskog.se/dynamic_sql.html

like image 56
codingbadger Avatar answered Nov 15 '22 05:11

codingbadger