In the below code i used single @partyID=750004
but now the scenario needs to use more @partyID
. FYI like 750005,750007,750009,7500011...
How can i loop using "For each"
BEGIN TRY
BEGIN TRAN
Declare @partyID bigint = 750004
IF NOT EXISTS (SELECT * FROM [QAdmin].[PartyLicenseInfo] WHERE PartyId = @partyID AND [State]='SC')
BEGIN
INSERT INTO QAdmin.PartyLicenseInfo (PartyId, [State], LicenseNumber, LicenseExpirationDate, CreatedBy, CreatedDate, ModifiedBy, ModifiedDate)
VALUES (@partyID, 'SC', 'SC1234', getdate()+360, 0, GETDATE(), null, null)
END
ELSE
BEGIN
UPDATE [QAdmin].[PartyLicenseInfo] SET LicenseExpirationDate = getdate()+360, ModifiedBy = 0, ModifiedDate = GETDATE()
WHERE PartyId = @partyID AND [State]='SC'
END
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
END CATCH
The best option is to get rid of the cursors and use a set based approach instead.
First, declare a table variable to store all IDs:
Then perform
INSERT INTO SELECT
andUPDATE
operations using this table variable:The above will insert new records into
PartyLicenseInfo
only if your originalNOT EXISTS
clause returnsTRUE
.The above will update records of
PartyLicenseInfo
havingPartyID
values contained in@partyID
and[State]='SC'
.