Dynamic SQL error converting nvarchar to int

前端 未结 2 663
北海茫月
北海茫月 2020-12-20 16:29

I have created a procedure in dynamic SQL which has a select statement and the code looks like:

ALTER PROCEDURE cagroup    (
    @DataID INT ,
    @days INT          


        
相关标签:
2条回答
  • 2020-12-20 17:03

    You need to CAST all numbers to nvarchar in the concatenation.

    There is no implicit VBA style conversion to string. In SQL Server data type precedence means ints are higher then nvarchar: so the whole string is trying to be CAST to int.

    SET @SQL =  'SELECT ' + @GName + ' AS GrName ,' + @BR
                  + CAST(@T_ID AS nvarchar(10)) + ' AS To_ID ,' ...
    

    Edit: Will A has a good point: watch for NULLs!

    0 讨论(0)
  • 2020-12-20 17:11

    If you have to build this kind of dynamic SQL, it is better to get the column information from the meta-data than to pass it around.

    Select * from Information_Schema.Columns Where Table_name=@TableName
    

    The you have to write an ugly cursor to build the SQL. Expect performance problems. I do lots of this during development to write code for me, but I don't dare run it in production.

    0 讨论(0)
提交回复
热议问题