Dynamic SQL Not Converting VARCHAR To INT (shouldn't anyway)

后端 未结 2 1950
天涯浪人
天涯浪人 2020-12-12 00:43

I\'m receiving an error:

Conversion failed when converting the varchar value \'INSERT INTO TableRowCount (IntFieldID, DecimalField) SELECT \'to data t

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 01:34

    You need to convert your @Start to a varchar.

    DECLARE @sql NVARCHAR(MAX)
    SET @sql = 'INSERT INTO TableRowCount (IntFieldID, DecimalField)
    SELECT ' + CAST(@start as nvarchar(20)) +', COUNT(*)
    FROM ' + @conn
    

    SQL Server implicitly converts between datatypes on concatenation or addition based on some fairly complex criteria. Suffice to say if you try to combine an int and a string it will always attempt to convert the string to an int unless you tell it otherwise explicitly.

    Below is a conversion chart for your reference from MSDN.

    enter image description here

提交回复
热议问题