Avatar of Declan Basile
Declan Basile
Flag for United States of America

asked on 

Loops in SQL server code

Is there a way to create a loop in SQL Server for the repeating code?

ALTER TRIGGER [dbo].[trigUpdateBitValues] 
ON [dbo].[CodeTrackingReqs] FOR INSERT, UPDATE
AS

	DECLARE @CumulativeSame As Integer
	DECLARE @CumulativeDontCare As Integer
	DECLARE @CodeTrackingReqId As Integer
	DECLARE @Attrib As TinyInt

	SET @CodeTrackingReqId = (SELECT Inserted.CodeTrackingReqId FROM INSERTED)
	SET @CumulativeSame = 0
	SET @CumulativeDontCare = 0

	SET @Attrib = (SELECT Inserted.Attrib1 FROM INSERTED)
	If @Attrib = 1
		SET @CumulativeSame = @CumulativeSame + POWER(2,0)
	If @Attrib = 2
		SET @CumulativeDontCare = @CumulativeDontCare + POWER(2,0)
	
	SET @Attrib = (SELECT Inserted.Attrib2 FROM INSERTED)
	If @Attrib = 1
		SET @CumulativeSame = @CumulativeSame + POWER(2,1)
	If @Attrib = 2
		SET @CumulativeDontCare = @CumulativeDontCare + POWER(2,1)

	SET @Attrib = (SELECT Inserted.Attrib3 FROM INSERTED)
	If @Attrib = 1
		SET @CumulativeSame = @CumulativeSame + POWER(2,2)
	If @Attrib = 2
		SET @CumulativeDontCare = @CumulativeDontCare + POWER(2,2)

	SET @Attrib = (SELECT Inserted.Attrib4 FROM INSERTED)
	If @Attrib = 1
		SET @CumulativeSame = @CumulativeSame + POWER(2,3)
	If @Attrib = 2
		SET @CumulativeDontCare = @CumulativeDontCare + POWER(2,3)

	UPDATE CodeTrackingReqs SET SameMask = @CumulativeSame, DontCareMask = @CumulativeDontCare
		 WHERE CodeTrackingReqId = @CodeTrackingReqId

Open in new window

Microsoft SQL Server

Avatar of undefined
Last Comment
Scott Pletcher

8/22/2022 - Mon