我有一个关于触发器的问题,我不确定这是否是正确的方法。但我有一个名为'tblWell'的表,其中id,welllonglat(地理)和welllong和welllat是十进制值类型。我正在使用lightswitch输入不支持地理值类型的数据。所以他们输入long和lat并插入。现在我需要在插入新记录后更新welllonglat(地理)值类型字段,所以我认为触发器可以工作。我不是那么好用触发器,所以想知道我如何得到welllong和welllat的值,如果新插入的记录,然后使用此功能更新记录welllonglat。 tblWell.WellLongLat = geography :: Point(tblWell.WellLat,tblWell.WellLong,4326)
现在说参数1为空..如何获取这些值..或者我怎么能这样做?代码低于谢谢
Alter TRIGGER trgAfterInsert ON [tblWell]
After INSERT
AS
begin
set nocount on
DECLARE @long decimal
DECLARE @lat decimal
update
[tblWell]
set tblWell.WellLongLat=geography::Point(tblWell.WellLat, tblWell.WellLong, 4326)
FROM
tblWell
end
go
根据下面的答案。以下代码应该可以工作,但我仍然得到一个空错误
Alter TRIGGER trgAfterInsert ON [tblWell]
After INSERT
AS
Begin
set nocount on
UPDATE A
SET WellLongLat = geography::Point(B.WellLat, B.WellLong, 4326)
FROM [tblWell] A
INNER JOIN INSERTED B
ON A.WellUID = B.WellUID
where B.WellLat IS NOT NULL and B.WellLong IS NOT NULL
END
go
这是表结构
CREATE TABLE [dbo].[tblWell](
[WellUID] [int] IDENTITY(1,1) NOT NULL,
[WellLocation] [varchar](500) NULL,
[WellLongLat] [geography] NULL,
[WarehouseID] [int] NULL,
[ProgrammedCost] [money] NULL,
[ProductionTypeID] [int] NULL,
[WellTypeID] [int] NULL,
[OperatorID] [int] NULL,
[WellLong] [decimal](9, 6) NULL,
[WellLat] [decimal](9, 6) NULL,
CONSTRAINT [PK_tblWell] PRIMARY KEY CLUSTERED
(
[WellUID] ASC
)
答案 0 :(得分:2)
您需要使用INSERTED
伪表:
ALTER TRIGGER trgAfterInsert ON [tblWell] AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
UPDATE A
SET WellLongLat = geography::Point(B.WellLat, B.WellLong, 4326)
FROM [tblWell] A
INNER JOIN INSERTED B
ON A.id = B.id
END
如果您想检查是否存在WellLat
和WellLong
,可以使用WHERE
:
ALTER TRIGGER trgAfterInsert ON [tblWell] AFTER INSERT
AS
BEGIN
SET NOCOUNT ON
IF EXISTS(SELECT 1 FROM INSERTED WHERE WellLat IS NOT NULL
AND WellLong IS NOT NULL)
BEGIN
UPDATE A
SET WellLongLat = geography::Point(B.WellLat, B.WellLong, 4326)
FROM [tblWell] A
INNER JOIN INSERTED B
ON A.id = B.id
WHERE B.WellLat IS NOT NULL AND B.WellLong IS NOT NULL
END
END
答案 1 :(得分:1)
Lamak的答案很好。这就是为什么你的工作不起作用的原因。您正在尝试从tbWell设置值。所以你的查询正在做的是遍历每一行并根据该行的WellLat和WellLong值设置WellLongLat。我想你在WellLat或WellLong的某个地方有一个空值,因此出现了空错误。
执行Lamak演示您从INSERTED表中获取刚刚插入的行的值,然后将它们与基于id列(应该是唯一的)插入的行匹配。因此,您最终会更新一行(如果id是唯一的)并且只更新行并使用新值。从技术上讲,我认为你不必在更新的Set部分中使用插入,但它有更好的形式。
小注意:你的声明在触发器中什么都不做,因为你从不使用它们所以没有指向它们