返回标识列值

时间:2016-03-30 21:46:42

标签: python sql-server

我有一些记录(> 1)需要插入数据库并将插入的记录返回到代码中(以及标识列中新形成的id)。我需要从python代码调用以将记录插入到sql server中。 我想在一次调用数据库时完成所有这些操作。我该怎么办?

1 个答案:

答案 0 :(得分:0)

将多个记录插入表时,可以使用INSERT语句中的OUTPUT子句访问新插入的数据。 MSDN Documentation

以下是一些要演示的代码:

/* Test table to demonstrate */
CREATE TABLE Test (ID INT IDENTITY(1, 1), Value VARCHAR(255));
GO
-- I'm using a table valued parameter to pass in the recordset
CREATE TYPE InputTable AS TABLE (Value VARCHAR(255));
GO

-- Test procedure to demonstrate
CREATE PROCEDURE dbo.InsertTest
    @In InputTable READONLY -- Pass in a recordset to insert
AS 

SET NOCOUNT ON

-- Create a temp table to return the results
CREATE TABLE #Test (ID INT, Value VARCHAR(255));

-- Insert the data into the test table
INSERT INTO Test (Value)
OUTPUT inserted.ID, inserted.Value INTO #Test -- Output the newly inserted records including the new ID into the temp table
SELECT *
FROM @In;

-- Return the inserted data including the new ID
SELECT * FROM #Test;

DROP TABLE #Test;
GO

-- Declare a variable that references the input
DECLARE @Input AS InputTable;

-- Add data to the variable
INSERT INTO @Input (Value)
SELECT name
FROM sys.objects;

-- Execute the test procedure
EXEC InsertTest @Input;
GO

DROP TABLE Test;
DROP PROCEDURE InsertTest;
DROP TYPE InputTable;