HiveBrain v1.2.0
Get Started
← Back to all entries
debugsqlMinor

Error updating sql server geography type in trigger

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
errortriggersqlupdatingtypegeographyserver

Problem

I have the following trigger in my database:

CREATE TRIGGER dbo.triggerGeocodedAddressUpdate ON dbo.Party AFTER UPDATE AS
    IF UPDATE(Latitude)
        UPDATE pt
        SET pt.GeocodedAddress = geography::Point(i.Latitude, i.Longitude, 4326)
        FROM dbo.Party AS pt INNER JOIN inserted AS i ON i.PartyId = pt.PartyId
        WHERE (i.Latitude IS NOT NULL AND i.Longitude IS NOT NULL);
        RETURN
    IF UPDATE(Longitude)
        UPDATE pt
        SET pt.GeocodedAddress = geography::Point(i.Latitude, i.Longitude, 4326)
        FROM dbo.Party AS pt INNER JOIN inserted AS i ON i.PartyId = pt.PartyId
        WHERE (i.Latitude IS NOT NULL AND i.Longitude IS NOT NULL);
        RETURN
GO


But every time I try to update a row in the Party table, I get an error, even if I don't change the Latitude or Longitude fields.

The error is:


geography::Point' failed because parameter 1 is not allowed to be null.

Any ideas? I'm pretty new to triggers, so I'm sorry if it's something simple and obvious.

Solution

Try this one. I have moved the conditional update into a single statement because the action you were taking was the same for both conditions. Also I have altered the way that you join to the INSERTED table so that it performs the filter pre-join:

CREATE TRIGGER dbo.triggerGeocodedAddressUpdate ON dbo.Party AFTER UPDATE AS
IF UPDATE(Latitude) OR UPDATE(Longitude)
    UPDATE pt
    SET pt.GeocodedAddress = geography::Point(i.Latitude, i.Longitude, 4326)
    FROM dbo.Party AS pt 
    JOIN 
    (
        SELECT PartyId, Latitude, Longitude
        FROM inserted
        WHERE (Latitude IS NOT NULL AND Longitude IS NOT NULL)
    ) AS i ON i.PartyId = pt.PartyId;
    RETURN
GO


I hope this helps you.

Code Snippets

CREATE TRIGGER dbo.triggerGeocodedAddressUpdate ON dbo.Party AFTER UPDATE AS
IF UPDATE(Latitude) OR UPDATE(Longitude)
    UPDATE pt
    SET pt.GeocodedAddress = geography::Point(i.Latitude, i.Longitude, 4326)
    FROM dbo.Party AS pt 
    JOIN 
    (
        SELECT PartyId, Latitude, Longitude
        FROM inserted
        WHERE (Latitude IS NOT NULL AND Longitude IS NOT NULL)
    ) AS i ON i.PartyId = pt.PartyId;
    RETURN
GO

Context

StackExchange Database Administrators Q#22967, answer score: 4

Revisions (0)

No revisions yet.