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;
SQL Server – 我常用语句的更多相关文章
- SQL Server性能常用语句
查看各表的数据行数 SELECT o.name, i. ROWS FROM sysobjects o, sysindexes i WHERE o.id = i.id AND o.Xtype = ORD ...
- SQL server 查询常用语句 2019.3.20
SQL查询语句 select ...列名 from 表名 投影查询 select sno num,2019-sage as birthday // 给列起别名 from student: 在每个学生姓 ...
- SQL Server中常用的SQL语句(转):
SQL Server中常用的SQL语句 转自:http://www.cnblogs.com/rainman/archive/2013/05/04/3060428.html 1.概述 名词 笛卡尔积.主 ...
- 处理SQL Server 异常常用步骤
处理SQL Server 异常常用步骤 SQL Server常见的问题主要是SQL问题造成,常见的主要是CPU过高和阻塞. 一.CPU过高的问题 1.查询系统动态视图查询执行时间长的sql语句 WIT ...
- SQL Server数据库常用函数
好久没学习新知识了.今天学了下sql的一些常用语句.人还是需要不断学习进步的 否则只能停滞不前. 先从最简单的一句开始说起吧. select *from 表名 这里*的含义 表示了表的各字段,以逗号隔 ...
- 【转载】SQL Server - 使用 Merge 语句实现表数据之间的对比同步
原文地址:SQL Server - 使用 Merge 语句实现表数据之间的对比同步 表数据之间的同步有很多种实现方式,比如删除然后重新 INSERT,或者写一些其它的分支条件判断再加以 INSERT ...
- Sql server的Merge语句,源表中如果有重复数据会导致执行报错
用过sql server的Merge语句的开发人员都应该很清楚Merge用来做表数据的插入/更新是非常方便的,但是其中有一个问题值得关注,那就是Merge语句中的源表中不能出现重复的数据,我们举例来说 ...
- SQL server 查看什么语句在使用临时表
SQL server 查询那些语句在使用临时表 最近在日常的性能测试工作中发现,数据库端的IO读写比较大,有规律的2-8M的波动,数据库的版本为 SQL server 2008 sp3. 这些IO操作 ...
- SQL Server中常用的SQL语句
1.概述 名词 笛卡尔积.主键.外键 数据完整性 实体完整性:主属性不能为空值,例如选课表中学号和课程号不能为空 参照完整性:表中的外键取值为空或参照表中的主键 用户定义完整性:取值范围或非空限制,例 ...
- MS SQL SERVER 2000 常用 Tran-SQL 语句
一.创建数据库:create database mydb-创建数据库mydbon primary-在primary文件组中( name = mydb_data1,filename = 'd:\sql ...
随机推荐
- oeasy教您玩转vim - 16 - # 行内贴靠
行头行尾 回忆上节课内容 跳跃 向前跳跃是 f 向后跳跃是 F 继续 保持方向是 ; 改变方向是 , 可以加上 [count] 来加速 还有什么好玩的吗? 动手 #这次还是用无配置的方式启动 vi - ...
- oeasy教您玩转vim - 70 - # 折叠细节
折叠细节 回忆上次 上次我们讲的是折叠 折叠有很多options foldlevel - 显示折叠层次 foldcolumn - 折叠树宽度 foldmethod - 折叠方式 manual - ...
- 工作单元(UnitOfWork) 模式 (2) .NET Core
1.工作单元(UnitOfWork)是什么? Maintains a list of objects affected by a business transaction and coordinate ...
- mybatisplus轻松完成一次模糊+分页查询
之前一直用mybatis+pageinfo完成模糊+分页查询,还需要手写sql语句,之前一直没做尝试,今天试了试mybatisplus一个人完成模糊+分页,挺简单的 有一个小插曲是,我的前端接受的da ...
- 关于SpringCloud Bus RemoteApplicationEvent 使用注意事项
最近使用SpringCloud Bus 用于服务直接消息通信,遇到一些问题,记录下来给一样碰到问题的你一个解决方案 开发环境 : springboot 2.3.9.RELEASE spring-clo ...
- 如何理解IOC中的“反转”和DI中的“注入”
在理解 IOC 中的"反转"和 DI 中的"注入"之前,首先要理解原本的控制流程. 在传统的应用程序中,对象之间的依赖关系通常由调用方(例如客户端或者上层模块) ...
- 算法·理论:KMP 学习笔记
\(\text{KMP}\) 笔记! 上次比赛,出题人出了一个 \(\text{KMP}\) 模板,我敲了个 \(\text{SAM}\) 跑了,但是学长给的好题中又有很多 \(\text{KMP}\ ...
- 【Spring-Security】Re14 Oauth2协议P4 整合SSO单点登陆
创建一个SSO单点登陆的客户端工程 需要的依赖和之前的项目基本一致: <?xml version="1.0" encoding="UTF-8"?> ...
- 国产的AI基础设施与国外的差距?仅以grpc与prpc做比较
搞AI,基础设施包括软件.硬件以及相关生态,多方面,这里只片面的取一个例子来说明国内外在AI基础设施上的区别,注意,这里只是片面截取. 高性能的rpc框架是搞AI的一个基础依赖软件,当然,国外也有与之 ...
- Tensorflow1.14中placeholder.shape和tf.shape(placeholder)的区别
最近在看TensorFlow的代码,还是1.14版本的TensorFlow的,代码难度确实比pytorch的难上不是多少倍,pytorch的代码看一遍基本能看懂个差不多,TensorFlow的代码看一 ...