我可以在SQL存储过程中分配变量吗?

时间:2010-04-06 14:44:44

标签: sql mysql sql-server stored-procedures

我正在做一个SQL Insert来填充我的表。我在一个表中有一个唯一的生成ID,我想在另一个表中用于我的连接。这可能吗?

.NET MVC -

using (SqlConnection connect = new SqlConnection(connections))
{
    SqlCommand command = new SqlCommand("ContactInfo_Add", connect);
    command.Parameters.Add(new SqlParameter("name", name));
    command.Parameters.Add(new SqlParameter("address", address));
    command.Parameters.Add(new SqlParameter("Product", name));
    command.Parameters.Add(new SqlParameter("Quantity", address));
    command.Parameters.Add(new SqlParameter("DueDate", city));
    connect.Open();
    command.ExecuteNonQuery();
}

SQL SERVER -

ALTER PROCEDURE [dbo].[Contact_Add]
@name varchar(40),
@address varchar(60),
@Product varchar(40),
@Quantity varchar(5),
@DueDate datetime
AS 
BEGIN
     SET NOCOUNT ON;

     INSERT INTO DBO.PERSON
     (Name, Address) VALUES (@name, @address)
     INSERT INTO DBO.PRODUCT_DATA
     (PersonID, Product, Quantity, DueDate) VALUES (@Product, @Quantity, @DueDate)
END

代码插入正常。我如何拉出自动生成的PersonID以在PRODUCT_DATA中使用?

2 个答案:

答案 0 :(得分:6)

您不需要使用SCOPE_IDENTITY(),使用OUTPUT和单个INSERT语句!
这确实需要SQL Server 2005及更高版本

试试这个:

设置表格

CREATE TABLE Test1 (PersonID int identity(1,1), Name varchar(40), Address varchar(60))
CREATE TABLE Test2 (PersonID int, product varchar(40),Quantity varchar(5),DueDate datetime)

创建程序

CREATE PROCEDURE TestSP
@name varchar(40),
@address varchar(60),
@Product varchar(40),
@Quantity varchar(5),
@DueDate datetime
AS 
BEGIN
     SET NOCOUNT ON;

     INSERT INTO Test1
             (Name, Address)
             OUTPUT INSERTED.PersonID, @Product, @Quantity, @DueDate
             INTO Test2
         VALUES 
             (@name, @address)

END

测试代码

exec TestSP 'name','address','product',123,'1/1/2010'
select * from Test1
select * from Test2

输出

PersonID    Name                 Address
----------- -------------------- -----------------------
1           name                 address

(1 row(s) affected)

PersonID    product   Quantity DueDate
----------- --------- -------- -----------------------
1           product   123      2010-01-01 00:00:00.000

(1 row(s) affected)

答案 1 :(得分:3)

您可以使用SCOPE_IDENTITY获取最后插入的标识值:

DECLARE @PersonID INT

INSERT INTO dbo.Person (Name, Address)
VALUES (@Name, @Address)

SET @PersonID = SCOPE_IDENTITY()

INSERT INTO dbo.Product_Data (PersonID, Product, Quantity, DueDate)
VALUES (@PersonID, @Product, @Quantity, @DueDate)