If the condition in the “IF” block is provided, we perform operations between the “BEGIN” and “END” blocks.
You can use it as follows.
1 2 3 4 | IF(1=1) BEGIN Select 1 END |
For a more detailed example, we create a table as below and add a few records.
1 2 3 4 5 6 7 8 9 10 11 | CREATE TABLE [dbo].[People]( [Name] [varchar](50) NOT NULL, [Age] [smallint] NOT NULL ) ON [PRIMARY] INSERT INTO [dbo].[People] ([Name],[Age]) VALUES ('Nurullah',34), ('Faruk',27), ('Hasan',54), ('Omer',2), ('Suleyman',64), ('Kerem',-1) |
Then, with the help of the following script, we find the maximum age in the table and if the maximum age is greater than 50, we delete that record or records from the table.
1 2 3 4 5 6 7 8 9 10 | SELECT * FROM [dbo].[People] DECLARE @MAX_AGE INT SELECT @MAX_AGE=MAX(age) FROM [dbo].[People] IF(@MAX_AGE>50) BEGIN DELETE FROM [dbo].[People] WHERE age=@MAX_AGE END SELECT * FROM [dbo].[People] |