将表名作为输入参数传递给SQL Server存储过程

时间:2016-06-21 13:18:08

标签: sql-server-2008 stored-procedures

我正在使用SQLserver 2008,我创建了一个存储过程来将多个记录插入表中。但是我无法将表名作为输入参数传递。

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

将错误视为

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".

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

这应解决您的问题

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&gt; SQLCMD.EXE -v DbName =&#34; Gannu&#34; tabn =&#34;巴拉斯&#34; startn =&#34; 20&#34; endn =&#34; 25&#34; -i T:\ SSHScript \ validate.sql

将数据库上下文更改为&#39; Gannu&#39;。

(受影响的一行)

答案 1 :(得分:0)

我可以在变量位置运行上面的查询和一些数据。

我发现唯一的问题是使用双引号(&#34;)作为值Act,Place。双引号不起作用。你需要单引号。

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