Checking some columns for specific values before insert/update using a trigger

纵饮孤独 提交于 2021-01-29 19:20:57

问题


I have a database FOO with several columns, among those I have one column "Url". I need to write a trigger before insert/update that will check the Url columns whether the newer value matches any existing values, i.e. "hello" except some predefined value. That means if "hello" is inserted or updated multiple times no error will happen otherwise it will check for duplicity. And if it finds some aborts the insertion update. This will also return some code so that my script calling for the insertion/update will know a failure has occurred. I know there might be other workarounds but I will need to have it this way. I am pretty new to SQL.

Foo {
    Url
}

Here is the algorithm

Before update insert
if new value of Url is not "hello1" o "hello 2" 
    check if new value of Url already exists in Foo.Url if so abort otherwise allow update/insert
     return something if aborted/success

回答1:


try something like this.. you'll need to index your table..

    IF EXISTS(SELECT URL FROM  Foo.Url)
      BEGIN 
       SELECT 'URL Exists Already'
      END
   ELSE 
     BEGIN 

      INSERT/UPDATE

     END 



回答2:


A unique constraint wouldn't do what you want but you could create an instead of trigger with content something like as:

Create TRIGGER [dbo].[Trig_Insert_XXX]
ON [dbo].[XXX]
INSTEAD OF INSERT
AS
BEGIN
  SET NOCOUNT ON;
  INSERT INTO xxx ([url], field1, field2, fieldN)
  SELECT [url], field1, field2, fieldN
  FROM inserted i
  WHERE i.url = 'hello' OR NOT EXISTS (SELECT * FROM xxx t2 WHERE t2.url = i.url);
END;



回答3:


I suppose you're looking for a UNIQUE constraint & a CHECK constraint as

CREATE TABLE Foo(
  Url VARCHAR(250) NOT NULL,
  CONSTRAINT UQ_Url UNIQUE(Url),
  CONSTRAINT CHK_Url CHECK (Url NOT IN ('hello1', 'hello2'))
);

See how it's working online.




回答4:


If you are using SQL Server 2008 or newer version you can use MERGE as well, the syntax is like the following :

MERGE [TableName] AS TARGET 
USING ( SELECT @UrlName ) AS SOURCE (UrlName) ON SOURCE.UrlName = TARGET.UrlName
WHEN MATCHED THEN
UPDATE SET ...
WHEN NOT MATCHED THEN INSERT ()
VALUES ();


来源:https://stackoverflow.com/questions/60286195/checking-some-columns-for-specific-values-before-insert-update-using-a-trigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!