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]python0045_转化为10进制数_int_integrate_integer_entire_整数
转化为10进制 回忆上次内容 上这次总结了四种进制 函数名 对应单词 进制类型 数字事例 前缀 bin() binary 2 0b1100001 0b oct() octal 8 0o141 0o h ...
- SQL Server AdventureWorks示例数据库
SQL Server AdventureWorks2008R2 数据字典 AdventureWorks2008R2示例数据库下载 AdventureWorks2008R2数据字典(官网) Addres ...
- 关于使用c++制作蓝牙连接,Windows版本
1 #define _CRT_SECURE_NO_WARNINGS 2 #pragma warning(disable : 4995) 3 #include <iostream> 4 #i ...
- 认识netty的基本组件
Java NIO VS Netty 有了 Java NIO,而且 Netty 也是基于 Java NIO 实现,那么为什么不能直接用 Java NIO 来实现网络通信模块呢? 接下来我就给大家解释一下 ...
- 9、SpringMVC之处理静态资源
9.1.环境搭建 9.1.1.在project创建新module 9.1.2.选择maven 9.1.3.设置module名称和路径 9.1.4.module初始状态 9.1.5.配置打包方式和引入依 ...
- 【Tutorial C】02 快速入门
在信息化.智能化的世界里,可能很早很早 我们就听过许多IT类的名词, C语言也在其中,我们侃侃而谈,到底C程序是什么样子? 让我们先看简单的一个例子: #include<stdio.h> ...
- 【Java】找不到此类异常
Java.lang.classNotFoundException 找不到此类异常: java.lang.ClassNotFoundException: org.springframework.web. ...
- 【转载】python画带方差的折线图(csdn上最简洁的代码之一附上)
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明. 原文链接:https://blog.csdn.net/a1920993165/article/ ...
- configure: error: Can't find GL/gl.h. Look for Mesa devel packages for your distro.
1. 安装文件查询工具 sudo apt install plocate 2. 查询头文件地址,shell命令: locate GL/gl.h 3. 为编译时指定其他的头文件查询地址: export ...
- A100和H100两款NVIDIA顶级双精度浮点数矢量运算芯片被限制对华出口——警醒
美国东部时间8月31日,NVIDIA公司宣布收到美政府通知停止对中国出口A100和H100两款NVIDIA顶级双精度浮点数矢量运算芯片,并且未来计算性能和数据传输性能高于A100的芯片都将禁止对中国出 ...