doesn't quotename work inside of exec?

点点圈 提交于 2019-12-23 17:49:55

问题


I'm trying to do something similar to this question. The answer recommends using quotename inside of an exec.

Similar to this:

declare @var nvarchar(128)
set @var = 'hello world'
exec('print ''' + quotename(@var) + '''')

But this doesn't work (Incorrect syntax near 'quotename'). Is the answer wrong?

I know I can generate the string first, put it in a variable then use it with exec sp_executeSql, but I would rather do it the way in the question if it can work...


回答1:


Best solution I could come up with for you is to pre-quote the value:

declare @var nvarchar(128);
set @var = 'hello world';
declare @quoted varchar(100);
select @quoted =  quotename(@var);
exec('print ''' + @quoted + '''');



回答2:


From the Transact-SQL Reference:

Execute a character string
{ EXEC | EXECUTE } 
    ( { @string_variable | [ N ]'tsql_string' } [ + ...n ] )
    [ AS { LOGIN | USER } ='name' ]
[;]

The syntax specification only allows string variables and string literals in this situation. Doesn't make sense, but calling functions returning strings is not allowed here.



来源:https://stackoverflow.com/questions/7029547/doesnt-quotename-work-inside-of-exec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!