Error in Dynamic SQL SP

让人想犯罪 __ 提交于 2020-01-06 08:24:13

问题


I Have created a procedure which has code like this:

   Create PROCEDURE Sample( @ID INT )
AS 
    BEGIN
    DECLARE @SQL NVARCHAR(max)
    DECLARE @SchemaName SYSNAME
    DECLARE @TableName SYSNAME
    DECLARE @DatabaseName SYSNAME


     SELECT  @SQL = 'Create Table ' + @DatabaseName + '.'
            + @SchemaName + '.' + @TableName
            + '_temp' + '('
    SELECT  @SQL = @SQL + 'ID int NOT NULL Primary Key, Name VarChar(10))'  

I Always get error as :

Msg 102, Level 15, State 1, Line 77 Incorrect syntax near ','.

Can anyone help me on this?


回答1:


Sometimes when using dynamic sql, I find it helpful to have it print the variable:

PRINT @SQL

That way you can take the output and look at it in the analyser




回答2:


Your string literal has an unfortunate length. Implicit string conversion from varchar to nvarchar truncates strings with a length between 4000 and 8000 characters to 4000 characters.

Use the N prefix before your string literal to avoid implicit string conversion.




回答3:


Don't use PRINT. Chances are that the PRINT output itself will be truncated with long text. Use

SELECT @SQL as [processing-instruction(x)] FOR XML PATH 

to inspect the values of such variables in SSMS.




回答4:


I changed your initial declaration of @SQL to DECLARE @SQL VARCHAR(max) and it worked (instead of NVARCHAR).



来源:https://stackoverflow.com/questions/5410740/error-in-dynamic-sql-sp

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