[Azure / mssql]如何获取插入查询记录集

时间:2017-09-03 12:37:00

标签: sql-server node.js azure express azure-sql-database

我正在使用mssql。 插入记录后,我想获取数据的ID。 但我不知道这么做的热情。 我的代码如下。 请给我答案。

var mssql = require('mssql');
mssql.connect(config.mssql, function(err) {
var request = new mssql.Request(); 
request.query('insert -----'),function(err, data) {
   console.log(data);
}

插入工作正常,但控制台日志是[未定义] ....

这是表格的ddl

SET ANSI_NULLS ON GO
SET QUOTED_IDENTIFIER ON GO
CREATE TABLE [dbo]。[功能](
    [id] nvarchar NOT NULL CONSTRAINT [DF_Feature_id] DEFAULT(CONVERT(nvarchar,newid(),(0))),
    [createdAt] datetimeoffset NOT NULL CONSTRAINT [DF_Feature_createdAt] DEFAULT(CONVERT(datetimeoffset,sysutcdatetime(),(0))),
    [updatedAt] datetimeoffset NULL,
    [version] [timestamp] NOT NULL,
    [删除] [bit] NULL DEFAULT((0)),
    [title] nvarchar NULL,
    [text] nvarchar NULL,
    [period_from] datetimeoffset NULL,
    [period_to] datetimeoffset NULL,
    [priority] [float] NULL,
主要密钥非集群 (
    [id] ASC
)WITH(STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF)

GO

1 个答案:

答案 0 :(得分:1)

使用OUTPUT子句。这是语法的一个例子......

IF OBJECT_ID('RandomTest.dbo.FeatureID_Capture', 'U') IS NOT NULL
DROP TABLE dbo.FeatureID_Capture;
GO      
CREATE TABLE dbo.FeatureID_Capture (
    Id NVARCHAR(50)
    );
GO

IF OBJECT_ID('RandomTest.dbo.Feature', 'U') IS NOT NULL
DROP TABLE dbo.Feature;
GO  
CREATE TABLE dbo.Feature (  
    id NVARCHAR(40) NOT NULL
        CONSTRAINT DF_Feature_id
        DEFAULT (CONVERT(NVARCHAR(40), NEWID(), (0))),
    createdAt DATETIMEOFFSET NOT NULL
        CONSTRAINT DF_Feature_createdAt
        DEFAULT (CONVERT(DATETIMEOFFSET, SYSUTCDATETIME(), (0))),
    updatedAt DATETIMEOFFSET NULL,
    version TIMESTAMP NOT NULL,
    deleted BIT NULL
        DEFAULT ((0)),
    title NVARCHAR (10) NULL,
    text NVARCHAR (10) NULL,
    period_from DATETIMEOFFSET NULL,
    period_to DATETIMEOFFSET NULL,
    priority FLOAT NULL,
    PRIMARY KEY NONCLUSTERED (id ASC)
    WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF)
    );
GO 
--=======================================================

INSERT dbo.Feature (title, text) 
    OUTPUT Inserted.id INTO dbo.FeatureID_Capture(Id)
VALUES ('t 1', 'txt 1'), ('t 2', 'txt 22'), ('t 3', 'txt 333');

-------------------------------------

SELECT *FROM dbo.FeatureID_Capture fic;

输出......

Id
--------------------------------------------------
4E9EB3CD-AD44-4837-9B87-BBB85308FFBF
B93983B6-C15A-4534-8AC4-EB9404964C09
FAFA678A-8416-490C-A871-3963EAB67B9F