SQL Server – 我常用语句
前言
旧没用又忘记了, 又没有 intellisense, 记入这里吧.
Reset Auto Increment
DBCC CHECKIDENT ('TableName'); -- check current DBCC CHECKIDENT ('TableName', RESEED, 0); -- reset to 0, next is 1
On/Off Auto Increment
Set Identity_Insert [TableName] Off; Set Identity_Insert [TableName] On;
很神奇.. On 的时候 insert 需要 Id, Off 反而不需要 Id...这不是反了吗?
官网的解释: Allows explicit values to be inserted into the identity column of a table, On 就是 allow 插入 Id
Int to String with Leading Zero
SELECT FORMAT(1, 'd2') --01
d2 就 2 位数, 3 就 3位数, 以此类推
Declare and Set Value
go declare @value nvarchar(max) = N'dada'; set @value = N'super'; -- select @value = count(*) from @table; print @value; go
If Else
go declare @value2 nvarchar(30) = 'keatkeat2'; if(@value2 = 'keatkeat') begin print 'yes'; end else begin print 'no'; end go
Ternary Operator
declare @value nvarchar(max) = IIF(1, 'yes', 'no');
For Loop
go declare @i int = 0; while(@i < 10) begin print @i; set @i = @i + 1; end go
Random String and Number
go SELECT CONVERT(INT, 5 * RAND()) SELECT SUBSTRING(CONVERT(varchar(255), NEWID()), 0, 9) select NEWID(); go
Random Data for Test Performance
create table
CREATE TABLE [dbo].[Test] ( [Id] int NOT NULL IDENTITY, [FirstName] nvarchar(450) NOT NULL DEFAULT '', [LastName] nvarchar(450) NOT NULL DEFAULT '', [Nickname] nvarchar(450) NOT NULL DEFAULT '', [Age] int NOT NULL DEFAULT 0, CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED ([Id] ASC) );
loop insert data
go declare @index int = 0; declare @length int = 1000000; while (@index < @length) begin insert into Test ([FirstName], [LastName], [Nickname], [Age]) values ( SUBSTRING(CONVERT(varchar(255), NEWID()), 0, 9), SUBSTRING(CONVERT(varchar(255), NEWID()), 0, 9), SUBSTRING(CONVERT(varchar(255), NEWID()), 0, 9), CONVERT(INT, 200 * RAND()) ); set @index = @index + 1; end go
batch insert data
insert into Test ([FirstName], [LastName], [Nickname], [Age]) select SUBSTRING(CONVERT(varchar(255), NEWID()), 0, 9), SUBSTRING(CONVERT(varchar(255), NEWID()), 0, 9), SUBSTRING(CONVERT(varchar(255), NEWID()), 0, 9), CONVERT(INT, 200 * RAND()) from Test;
Create Variable Table and Loop
-- create temp table and loop it go declare @temp table (name nvarchar(max), [index] int identity(1,1)); insert into @temp (name) values ('keatkeat'), ('xinyao'); declare @i int = 0; declare @length int; select @length = count(*) from @temp; while(@i < @length) begin declare @value nvarchar(max) select @value = name from @temp order by [index] offset @i rows fetch next 1 rows only; print @value; set @i = @i + 1; end go
Select into + row number
select value, ROW_NUMBER() over(order by (select null)) as [RowNumber] from STRING_SPLIT('a,b,c', ',');
String Contains
declare @value nvarchar(max) = IIF('value' like '%lu%', 'yes', 'no'); --关键 'value' like '%lu%'
Date Format
参考: Stack Overflow – How to display the date as mm/dd/yyyy hh:mm Am/PM using sql server 2008 r2?
select FORMAT(cast('2022-12-01 09:07:02.805 +08:00' as datetimeoffset), 'MM/dd/yyyy hh:mm:s tt');
Date Adjustment
select CreatedDate, ValidHour, DATEADD(HOUR, ValidHour, CreatedDate) as ValidUntil from voucher;
Try Catch Throw
begin try throw 50000, 'custom error',1; end try begin catch print(ERROR_MESSAGE()); -- custom error. print(ERROR_SEVERITY()); -- 16 print(ERROR_STATE()); -- 1 end catch
注: 在 if statment 里面 throw 要加分号 ; 哦. 参考: Stack Overflow – SQL only a throw inside if statement
Get First Row After Group By (use CTE)
with cte as ( select FORMAT(DateCreated, 'dd-MMM hh:mm tt') as [Date], DateCreated, CustomerName, CustomerContact, CustomerEnquiry, CustomerAction, GoogleClickId, ROW_NUMBER() over (partition by CustomerName, CustomerContact order by DateCreated desc) as RowNumber from Conversion where DateCreated >= '2023-02-17' and CustomerContact not like '%test%' ) select [Date], CustomerName, CustomerContact, CustomerEnquiry, CustomerAction, GoogleClickId from cte where RowNumber = 1 order by DateCreated desc;
Group by 后那每个 group 的第一条数据
Get All Table Column Name
SELECT STRING_AGG ('['+ COLUMN_NAME +']', ', ') AS [COLUMNS] FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'AccountsReceivable';
without computed column
select STRING_AGG ('['+ COLUMN_NAME +']', ', ') AS [COLUMNS] from INFORMATION_SCHEMA.COLUMNS ColumnTable left join sys.computed_columns ComputedColumnTable on OBJECT_NAME(ComputedColumnTable.object_id) = ColumnTable.TABLE_NAME and ComputedColumnTable.[name] = ColumnTable.COLUMN_NAME WHERE ComputedColumnTable.object_id is null and ColumnTable.TABLE_NAME = 'AccountsReceivable';
Testing Performance
DBCC DROPCLEANBUFFERS --清空执行计划缓存 DBCC FREEPROCCACHE --清空数据缓存 SET STATISTICS IO ON; SET STATISTICS TIME ON; left join TestChild WITH (INDEX([IX_TestChild_TestId])) --强制使用 index -- 强制 join pattern left hash join left merge join left loop join
Disable Index and Constraints
alter index [IX_IndexName] on [TableName] disable; alter index [IX_IndexName] on [TableName] rebuild;