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 Change data type for Primary Key column (IDENTITY setting will be persisted): — drop primary key constraint ALTER TABLE [dbo].[SampleTable]…
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
T-SQLpowered

SQLCMD - Basic commands

Check if SQLCMD mode is enabled in SSMS: :setvar __IsSqlCmdEnabled “True” GO IF N’$(__IsSqlCmdEnabled)’ NOT LIKE N’True’ BEGIN PRINT N’SQLCMD mode must be enabled to successfully execute this script.’; SET NOEXEC ON; END GO Declare database name as variable and switch database context: :SETVAR Database “MyDatabase” USE [$(Database)] GO Execute/Include…
T-SQLpowered

SELECT - Basic

Select constant value: SELECT 1 — number SELECT ‘A’ — character SELECT 1, ‘A’ — multiple values Select expression: SELECT 1 + 1 SELECT ‘A’ + ‘A’ SELECT LEFT(‘ABC’, 1) + ‘BC’ Use an asterisk to show all columns: SELECT * FROM sys.tables Select specific columns: SELECT [object_id], [name] FROM…