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

后端 未结 2 1949
天涯浪人
天涯浪人 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:21

    A better way than trying to concatenate an integer is to pass it in as a strongly-typed parameter:

    DECLARE @start INT = 1;
    
    DECLARE @sql NVARCHAR(MAX) = N'INSERT ...
      SELECT @start, COUNT(*) FROM ' + @conn;
    
    EXEC sp_executesql @sql, N'@start INT', @start;
    
    0 讨论(0)
  • 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

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