在 SQL Server 中,如何创建表的引用变量?
我当前正在使用 sp_executesql 来执行具有动态表名的 T-SQL 语句。然而,看到这样的东西真的很难看:
set @sql = 'UPDATE '+Table_Name+' SET ... WHERE '+someVar+' = ... AND '+someVar2' = ...'
sp_executesql @sql
我宁愿拥有一个 TABLE 变量,其中是对表的引用,所以我可以这样做:
UPDATE TableRef SET ... WHERE ...
因为当我有很长的 T-SQL 语句时,它会得到由于字符串中的格式,真的很难阅读。
任何建议都会有帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不将参数传递给 sp_executeSQL 呢?
我也想看看这篇文章。
Why don't you pass the parameters to sp_executeSQL instead?
I'd also have a look at this article too.
你不能。如果要在 SQL 中使用动态表名,则必须将其连接到字符串中。
如果查询中对表名有很多引用,则可以通过为表名添加别名来缩短它,对于所有其他实例,请使用别名。
例如,
使用这样的动态 SQL 时要非常小心。确保防范 SQL 注入。
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.
Just be very very careful when using dynamic SQL like this. Make sure you guard yourself against SQL injection.