I want to insert multiple rows into a database if they don't already exist, swapping out one columns value for each insertion. Below is some pseudo code of the goal:
IF NOT EXISTS (SELECT [ChangeReason] FROM BudgetAndAuthorizationChangeReasons WHERE [ChangeReason]= ('Other','Scope Change'))
INSERT INTO [dbo].[BudgetAndAuthorizationChangeReasons]
([ChangeReason]
,[IsActive]
,[CreatedByUser]
,[CreatedOn]
,[LastUpdatedByUser]
,[LastUpdatedOn])
VALUES
( ('Other','Scope Change')
,'true'
,'system'
,GETDATE()
,null
,null)
GO
In other words, if a row with ChangeReason='Other'
already exists, nothing will happen. If it does not exist, then it will be inserted with all the other values outlined as above (IsActive=true, etc). This will be repeated for each element in the array : ('Other','Scope Change')
EDIT:
I have written a stored procedure to take care of the dirty work for me. Is it possible to call this automatically for every element in the array? Or do I need X different exec statements?
IF EXISTS ( select * from sys.procedures where name='SafeInsert_BudgetAndAuthorizationChangeReasons') begin
DROP PROC SafeInsert_BudgetAndAuthorizationChangeReasons
end;
GO
create procedure SafeInsert_BudgetAndAuthorizationChangeReasons @Reason varchar(50)
as
begin
IF NOT EXISTS (SELECT [ChangeReason] FROM BudgetAndAuthorizationChangeReasons WHERE [ChangeReason]= @Reason)
INSERT INTO [dbo].[BudgetAndAuthorizationChangeReasons]
([ChangeReason]
,[IsActive]
,[CreatedByUser]
,[CreatedOn]
,[LastUpdatedByUser]
,[LastUpdatedOn])
VALUES
(@Reason
,'true'
,'system'
,GETDATE()
,null
,null);
end;
GO
exec SafeInsert_BudgetAndAuthorizationChangeReasons @Reason='Other';
-- goal: auto-exec for every element in ('Other','Scope Change')