T-SQLpowered

WHILE

Iterate with MIN/MAX Id. Doesn’t perform well for broken number sequences. DECLARE @Current_Id INT DECLARE @Max_Id INT DECLARE @Ids TABLE ( [Id] INT) INSERT INTO @Ids ([Id]) SELECT [Id] FROM (VALUES (1),(2),(3)) [v] ([Id]) SELECT @Current_Id = MIN([Id]) FROM @Ids SELECT @Max_Id = MAX([Id]) FROM @Ids WHILE @Current_Id <= @Max_Id…

Read more
T-SQLpowered

Basic operations

Split long string to multiple lines (\ separator): SELECT ‘abc\ def’ AS [Result]; SELECT 0xabc\ def AS [Result];  
T-SQLpowered

CREATE TABLE

Create Table with clustered Primary Key on Identity column: CREATE TABLE [dbo].[SampleTable] ( [Id] INT IDENTITY (1,1) NOT NULL, CONSTRAINT [PK_SampleTable] PRIMARY KEY CLUSTERED ([Id]) )  
T-SQLpowered

Table Type

Declare with PK constraint, insert and retrieve data: CREATE TYPE [dbo].[utt_Generic_Int] AS TABLE ( [Id] [INT] NOT NULL PRIMARY KEY CLUSTERED ) GO DECLARE @Ids utt_Generic_Int INSERT INTO @Ids ( [Id] ) VALUES (1), (2), (3) SELECT * FROM @Ids GO  

Read more
T-SQLpowered

Jobs

Enable/Disable job: — enable EXEC msdb.dbo.sp_update_job @job_name=’SampleJobName’, @enabled = 1 — disable EXEC msdb.dbo.sp_update_job @job_name=’SampleJobName’, @enabled = 0    
T-SQLpowered

MERGE

Using OUTPUT clause: MERGE INTO [dbo].[TargetTable] [trg] USING ( SELECT [ID], [Value], [OtherValue] FROM [dbo].[SourceTable] ) AS [src] ON 1 = 0 WHEN NOT MATCHED THEN INSERT ( [ID],[Value] ) VALUES ([src].[ID], [src].[Value]) OUTPUT [Inserted].[ID], [Inserted].[Value], [src].[OtherValue]  

Read more
T-SQLpowered

UPDATE

Update with the expression: UPDATE [dbo].[SampleTable] SET [Col1] = @a + @b + @c Update using the .WRITE() clause: UPDATE [dbo].[SampleTable] SET [Col1].WRITE(‘New Value, 0, NULL) UPDATE [dbo].[SampleTable] SET [Col1].WRITE(@a + @b + @c, 0, NULL) UPDATE [dbo].[SampleTable] SET [Col1].WRITE(@x, 500, 1000)  
T-SQLpowered

ALTER TABLE

Add New Column: ALTER TABLE [dbo].[SampleTable] ADD [NewColum_1] NVARCHAR(MAX) — will be added as NULLable ALTER TABLE [dbo].[SampleTable] ADD [NewColum_1] NVARCHAR(MAX) NULL ALTER TABLE [dbo].[SampleTable] ADD [NewColum_1] NVARCHAR(MAX) NOT NULL Add Primary Key: ALTER TABLE [dbo].[SampleTable] ADD CONSTRAINT PK_Sample_Table PRIMARY KEY CLUSTERED (Id) Change data type for Primary Key column…
T-SQLpowered

INSERT - Basic

Insert one row with default values for all table columns: INSERT INTO [dbo].[SampleTable] DEFAULT VALUES SELECT INTO and specify a filegroup (2016 SP2+): SELECT * INTO [dbo].[SampleTable_Copy] ON [OtherFilegoup] FROM [dbo].[SampleTable]  

Read more