Click here to Skip to main content
15,789,698 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a stored procedure something like below
CREATE PROCEDURE [dbo].[spInsert]
@name1 varchar(100),
@name2 varchar(100),
@Id int,
@LastUpdated datetime,
@Volume decimal

declare @tableName varchar(100) = @name1 + '_' + @name2
INSERT INTO  [dbo]. [@tableName]
 VALUES( @Id , @LastUpdated , @Volume)

My issue is the table name in the procedure is a variable created inside the procedure. It says the table variable @tableName should be declared.

Also tried dynamic sql (im not sure what i did is dynamic sql or not) like
EXEC(' INSERT INTO  [dbo]. [' + @tableName + ']   
 VALUES( ' + @Id + ',' + @LastUpdated + ',' + @Volume + ')' )

This shows no error but record is not added to table.

It would be great if someone let me know how to proceed on this.


[edit]SHOUTING removed - OriginalGriff[/edit]
Updated 10-Apr-23 23:34pm
OriginalGriff 28-Jun-11 7:16am    
DON'T SHOUT. Using all capitals is considered shouting on the internet, and rude (using all lower case is considered childish). Use proper capitalisation if you want to be taken seriously.

try changing your dynamic insert statement as below

' INSERT INTO [dbo]. [' + @tableName + ']
VALUES( ' + cast(@Id as varchar(20)) + ',' + cast(@LastUpdated as varchar(30)) + ',' + cast(@Volume as varchar(30)) + ')' )
Share this answer
One of the things I always do when creating dynamic sql is to 'print' it first to see what it is producing: great way to mitigate any errors. Anyway, along those lines try something like:

declare @Id int, @LastUpdated datetime, @Volume decimal
set @Id = 1
set @LastUpdated = getdate()
set @Volume = 10
declare @Sql nvarchar(max), @tableName nvarchar(100)
set @TableName = 'dummy'
set @Sql =
'insert into [dbo].' + @tableName + ' (Id, LastUpdated, Volume)
 values(' + convert(nvarchar, @Id) + ',''' + convert(nvarchar, @LastUpdated) + ''',' + convert(nvarchar, @Volume) + ')'
print @Sql
-- exec sp_executesql @Sql

uncomment the exec when you are ready and, obviously, only use the part pertinent to your requirement.
Share this answer
Sorry for the delayed reply. I made a mistake while forming the SQL query to be executed using exec(@sql). The datetime data (column named 'LastUpdated') i tried to insert without quotes (string n date type data should be in quotes for insert). Once I corrected that my procedure worked fine.

Thanks all for reply and the above 2 answers looks correct though i did not try as I found what my prob was.

Share this answer
so how can i get insertred record id and output it
Share this answer
Richard Deeming 11-Apr-23 5:48am    
Your question is not a "solution" to someone else's question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900