I have written a Create trigger and it shows me some error on Incorrect Syntax near
CREATE TRIGGER [dbo].[News_data] ON [dbo].[News]
AFTER INSERT
AS
declare @NID uniqueidentifier;
select @NID = NEWID();
BEGIN
SET NOCOUNT ON;
INSERT INTO [ABC].[News](
@NID,
[Name], //<-- Incorrect Syntax near [Name]
[GeoLoc])
SELECT
[Name],
[GeoLoc]
FROM inserted
END
答案 0 :(得分:5)
Your variable declaration is wrong with column list, if news
table has primary column for which you are referring to @NID
then use that column name instead :
INSERT INTO [dbo].[News] (PK, [Name], [GeoLoc])
SELECT @NID, [Name], [GeoLoc]
FROM inserted
答案 1 :(得分:2)
打算发布示例代码,但是Yogesh已经提供了答案
CREATE TRIGGER [dbo].[Customers_data] ON Customers
INSTEAD OF INSERT AS
DECLARE @NID INT = NEWID()
BEGIN
SET NOCOUNT ON;
INSERT INTO Customers(
CustomerID, -- <-- ColumnName instead of its value
CustomerName, -- <-- Incorrect Syntax near [Name]
ContactName)
SELECT
@NID
CustomerName,
ContactName
FROM inserted
END
您可能需要查看的其他信息是ID。如果在一个事务中插入了多个记录,那么插入的记录将具有相同的“ NewId”。不确定是不是您想要的那种,但是由于我怀疑@NID是主键,因此您可能想看看它。
编辑:确保触发器仍可与批量插入一起使用。意味着在一个事务中插入了多个记录,因此插入的SELECT * FROM将包含多个记录,而您不希望它们使用相同的@NID值。
CREATE TRIGGER [dbo].[Customers_data] ON Customers
INSTEAD OF INSERT AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Customers(
CustomerID, -- <-- ColumnName instead of its value
CustomerName,
ContactName)
SELECT
NEWID(), -- <-- If the 'FROM inserted' contain multiple columns
CustomerName,
ContactName
FROM inserted
END