如何执行很长的动态sql语句?
我记得当时我会制作一整堆 nvarchar(4000)
变量,在它们增长时检查它们的长度,在它们填满时将它们切换出来,然后将整个混乱连接在一起执行调用。我想知道是否有更简单的方法可以做到这一点。
谢谢!
编辑:
代码示例,显示我搞砸了 case 语句
DECLARE @sql NVARCHAR(MAX)
SELECT @sql = CAST(N'SELECT ' AS NVARCHAR(MAX))
DECLARE @Index INT
SELECT @Index = 0
WHILE (@Index < 1000)
BEGIN
SELECT @sql = CAST(@sql AS NVARCHAR(MAX)) + CAST(N' ' AS NVARCHAR(MAX)) + CAST( CASE @Index WHEN 1 THEN N' ' END AS NVARCHAR(MAX))
SELECT @Index = @Index + 1
END
SELECT @sql = CAST(@sql AS NVARCHAR(MAX)) + CAST(1 AS NVARCHAR(MAX))
SELECT LEN(@sql)
EXECUTE sp_executesql @sql
I remember back in the day I would make a whole wack of nvarchar(4000)
vars, check the length of them as they grew, switch them out as they filled up and then concatenate the whole mess together for the exec call. I was wondering if there was an easier way of doing it.
Thanks!
Edit:
Code Sample, shows me screwing up the case statement
DECLARE @sql NVARCHAR(MAX)
SELECT @sql = CAST(N'SELECT ' AS NVARCHAR(MAX))
DECLARE @Index INT
SELECT @Index = 0
WHILE (@Index < 1000)
BEGIN
SELECT @sql = CAST(@sql AS NVARCHAR(MAX)) + CAST(N' ' AS NVARCHAR(MAX)) + CAST( CASE @Index WHEN 1 THEN N' ' END AS NVARCHAR(MAX))
SELECT @Index = @Index + 1
END
SELECT @sql = CAST(@sql AS NVARCHAR(MAX)) + CAST(1 AS NVARCHAR(MAX))
SELECT LEN(@sql)
EXECUTE sp_executesql @sql
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
sp_executesql
接受 NVARCHAR 类型的参数( MAX),最大可增长至 2GB。不需要任何花招,因为 NVARCHAR(MAX) 类型支持所有字符串操作(连接、替换等):sp_executesql
accepts a parameter of type NVARCHAR(MAX) which can grow up to 2GB. There is no need for any gimmick, since the NVARCHAR(MAX) type supports all the string operations (concatenation, replacing etc):EXEC (@YourSQL)
或sp_exectesql
如果您希望继续构建动态 SQL 并执行。EXEC (@YourSQL)
ORsp_exectesql
if you wish to continue to build onto your dynamic SQL and execute.