SQL Dynamic Stored Procedure

BigH61 581 Reputation points
2023-05-29T06:14:54.23+00:00

I hope some one can put me out of my misery with what should be a simple issue but I am unable to see what I have done wrong. I am relatively new to SQL but this should be a straight forward conversion.

I have a simple SQL stored procedure as below

INSERT INTO Country (Country)
VALUES (@NewResourceName);

I wish to convert this into a dynamic stored procedure and have tried numerous variations of the below

DECLARE @sSQL nvarchar(400);
SET @sSQL = 'INSERT INTO '+@Resource+'('+@Resource+')'+
' VALUES ('+@NewResourceName+');'
Execute sp_executesql @sSQL;

I receive an error invalid column name for what ever I pass as parameter @NewResourceName

Thank you in advance.

SQL Server | Other
0 comments No comments
{count} votes

Answer accepted by question author
  1. Viorel 125.6K Reputation points
    2023-05-29T06:56:42.74+00:00

    Try this:

    set @sSQL = 'INSERT INTO ' + @Resource + ' ('+ @Resource + ')' + ' VALUES (@NewResourceName)'
    
    exec sp_executesql @sSQL, N'@NewResourceName nvarchar(max)', @NewResourceName
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2023-05-29T06:57:11.4566667+00:00

    Hi @BigH61

    I created an empty table test.

    You can try this dynamic SQL.

    DECLARE @sSQL nvarchar(400)
    DECLARE @TableName nvarchar(max)
    DECLARE @ColName nvarchar(max)
    DECLARE @Insert nvarchar(max)
    set @TableName = 'test'
    set @ColName = 'A'
    set @Insert = 'j24h'
    set @sSQL = N'INSERT INTO ' + @TableName + '(' + @ColName + ')' + ' VALUES (' +  QUOTENAME(@Insert,'''') + ');'
    print @sSQL;
    Exec sp_executesql @sSQL,N'@TableName nvarchar(max),@ColName nvarchar(max),@Insert nvarchar(max)',@TableName,@ColName,@Insert;
    

    Output:

    User's image

    If you need to write into stored procedures, you can refer to this official document, which contains an example of dynamic insertion.

    https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-ver16

    Best regards,

    Percy Tang

    1 person found this answer helpful.

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.