0

I'm using SQLserver 2008 and I have created a stored procedure to insert multiple records into a table. But I'm unable to pass the table name as a input parameter.

USE $(DbName)
GO
DECLARE @command varchar(1000),@i int, @tabname as varchar(100)
set @tabname = $(tabn)
set @i = $(startn) 
while @i < $(endn)
BEGIN
SET @command = 'Insert into '+($tabn)+'(Name,Address) Values("Act'+ CAST(@i AS varchar) +'","Place '+ CAST(@i AS varchar) +'")'
EXEC (@command)
SET @i = @i + 1
END
Go

Getting error as

C:\Program Files\Microsoft SQL Server\100\Tools\Binn>SQLCMD.EXE -v DbName="Gannu"
startn="90" endn="180" tabn="Sandeep" -i U:\SSHScript\recvariable.sql
Changed database context to 'Gannu'.
Msg 126, Level 15, State 1, Server BRANCH1_WIN, Line 6
Invalid pseudocolumn "$tabn".

Can someone help me on this?

2 Answers 2

1

This should resolve your issue

USE $(DbName)
GO
DECLARE @command varchar(1000),@i int, @tabname as varchar(100)
set @tabname = '$(tabn)'
set @i = $(startn) 
while @i < $(endn)
BEGIN
SET @command = 'Insert into ' + @tabname + '(Name,city) Values("Act'+   CAST(@i AS varchar) +'","Place '+ CAST(@i AS varchar) +'")'
EXEC (@command)

SET @i = @i + 1
END
Go

C:\Program Files\Microsoft SQL Server\100\Tools\Binn>SQLCMD.EXE -v DbName="Gannu" tabn="Bharath" startn="20" endn="25" -i T:\SSHScript\validate.sql

Changed database context to 'Gannu'.

(1 rows affected)

Sign up to request clarification or add additional context in comments.

Comments

0

I could run the above query with some data in places of variables.

The only thing, I found problematic was to use double quotes (") for values Act, Place. Double quotes won't work. You need single quotes there.

USE VAIBHAVDB
if OBJECT_ID('MyTable', 'U') is not null
drop table MyTable
Go
create table MyTable (name varchar(500), address varchar(500))
GO
DECLARE @command nvarchar(1000),@i int, @tabname as varchar(100)
set @tabname = 'MyTable'
set @i = 1
while @i < 5
BEGIN
SET @command = 'Insert into '+@tabname +'(Name,Address) Values('+ '''' + 'Act' + CAST(@i AS varchar) + '''' +' ,'+''''+'Place '+ CAST(@i AS varchar) +''''+')'
PRINT @command
EXEC (@command)
SET @i = @i + 1
END
Go

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.