如何使用SQL Server中的存储过程在单个查询中插入多行

时间:2017-12-03 15:50:19

标签: sql-server sql-server-2008 tsql stored-procedures sql-server-2005

CREATE PROCEDURE Usp_insertgender
    (@gendervalues VARCHAR(MAX))
AS
BEGIN
    INSERT INTO sparsha.dbo.Genders ([GenderName])
    VALUES @gendervalues;
END

我尝试了上述程序,但收到错误

  

Msg 102,Level 15,State 1,Procedure Usp_insertgender,Line 10
  ' @ gendervalues'附近的语法不正确。

我将@gendervalues值传递为(' 1'),(' 2')

2 个答案:

答案 0 :(得分:3)

最简单的方法可能是定义TVP

CREATE TYPE myTVPType AS TABLE( v VARCHAR(50));  
GO  

CREATE PROCEDURE Usp_insertgender (@gendervalues myTVPType READONLY) 
AS 
BEGIN
  INSERT INTO sparsha.dbo.Genders ([GenderName]) 
  SELECT v
  FROM @gendervalues; 
END;

如何称呼它:

DECLARE @tvp AS myTVPType;  

INSERT INTO @TVP (v)  
VALUES ('1'),('2');

EXEC Usp_insertgender @TVP;  
GO  

答案 1 :(得分:1)

试试这个:(使用动态SQL)

CREATE PROCEDURE Usp_insertgender
    (@gendervalues VARCHAR(MAX))
AS
BEGIN
    DECLARE @sql nvarchar(2000)

    SET @sql = N'INSERT INTO sparsha.dbo.Genders ([GenderName])
    VALUES ' + @gendervalues

    EXEC sp_executesql @sql
END