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

2

9

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.

Septuple answered 18/6, 2010 at 10:18 Comment(3)
btw, not SET sql = ... but SET @sql = ...Arrestment
Yeah, thanks for the fixes. I kept getting blockquote when I pressed @. I wasn't aware that I could do it like this. Thanks.Sustentation
ón: the product is called "SQL Server", not "MSSQL".Joggle
D
1

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

I'd also have a look at this article too.

Delbert answered 18/6, 2010 at 10:21 Comment(0)
C
0

You can't. If you want to use a dynamic table name in your SQL, you have to concatenate it into your string.

If you have a lot of references to the table name within your query, you can shorten it by aliasing the table name, and for all other instances, use the alias.

e.g.

SET @SQL = 'UPDATE t SET.... FROM ' + @TableName + ' t WHERE ....'

Just be very very careful when using dynamic SQL like this. Make sure you guard yourself against SQL injection.

Cynical answered 18/6, 2010 at 10:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.