I have a stored procedure written to insert a new row to a table and I wish to generalize it so a single procedure may add rows to any of a range of tables depending on the input. Here is the query which presently defines the individual case:
CREATE PROCEDURE [Test].[NO001CreateRow]
@InstanceID char(5)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO dbo.NO001 (InstanceID)
VALUES (@InstanceID)
END
GO
This seems to work fine. InstanceID is the name of a key-value column in the table NO001. The procedure inserts a new row into NO001 with the value of InstanceID set to the input @InstanceID.
Here is the query which defines the procedure I have made for the general case:
CREATE PROCEDURE [Test].[GenCreateRow]
@TableID nchar(5),
@InstanceID nchar(5)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @sql nvarchar(max) = 'INSERT INTO dbo.' + @TableID + ' (InstanceID)
VALUES (' + @InstanceID + ')'
EXEC sp_executesql @sql
END
GO
As far as I can tell, this procedure should add to a table identified by the input five-character @TableID a new row with column InstanceID populated by the input @InstanceID. However, when I run the procedure with parameters @TableID=NO001 and @InstanceID=XXXXX the code breaks and returns the error message Invalid column name 'XXXXX'.
I do not understand why it tries to find a column in table @TableID titled @InstanceID. I understood the column definition to be the parenthetical InstanceID on line 7, and I don't believe InstanceID should automatically assume the value of @InstanceID. Does anyone know what's going on here?
Here is the code displayed on execution:
DECLARE @return_value int
EXEC @return_value = [Test].[GenCreateRow]
@FormID = N'NO001',
@InstanceID = N'XXXXX'
SELECT 'Return Value' = @return_value
GO
sp_executesql?EXECtoPRINTand have a look. Might just be missing quotes around your value strings.