I have the following stored procedure:
CREATE PROCEDURE [cafgAddCoreID]
@HoldingName nvarchar (50) = null
@CountStart int = 0,
AS
DECLARE @sql nvarchar (50)
DECLARE @bit nvarchar (200)
BEGIN
SET @bit = 'MTR1- + CAST ((' + @CountStart + ' + ROW_NUMBER()
OVER (ORDER BY [FindNo])) AS NVARCHAR(10))'
SET @sql = 'INSERT INTO ' + @HoldingName + '([CoreID])
SELECT (' + @bit + ') FROM [DectectoristMetalFinds]'
EXEC @sql
END
But when I run:
EXEC [cafgAddCoreID] 'Table1', 9
I get
Conversion failed when converting the varchar value 'MTR1- + CAST ((' to data type int.
Running
INSERT INTO [Table1] ([CoreID])
SELECT ('MTR1-' + CAST ((0 + ROW_NUMBER() OVER (ORDER BY FindNo))
AS NVARCHAR(10))) AS CoreID FROM [Table2]
works so I know the method is right, but obviously not in an stored procedure.
@sqlbefore you exec it?MTR1-is surrounded by the appropriate number of apostrophes. Also, heeeeello SQL injection attacks.PRINT @sql;but based on the error you won't get that far. You need to case your @CountStart as a string in order to build the string.