一些常用的sql语句

1 、创建表
2、追加字段-删除字段
3、随机数
4、时间转字符串
5、查询年、月、日
6、Case、When、Then
7、获取新增Sql的Id
8、增加序号
9、Try-Catch
10、与时间相关的Sql查询
11、查询sql执行时间和CPU占用时间和I/O操作情况
12、替换
13、删除表、清空表、复制表
14、清理日志
15、锁表查询、解锁
16、Sql语句性能Top10 
17、查询 表信息
18、查询表说明
19、查询表字段详情
ok!!!
1 、创建表
--删除表
--DROP TABLE [dbo].[表名]

--创建表
CREATE TABLE [dbo].[System_Code_InstallationPeriod] (
[Id] INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
[Name] nvarchar(50) NULL DEFAULT '默认值',
[TypeId] INT NULL,
[Money] money NULL,
[CreatePeople] nvarchar(50) NULL ,
[CreateTime] datetime NULL ,
[ModifyPeople] nvarchar(50) NULL ,
[ModifyTime] datetime NULL
)

--添加表说明
EXECUTE sp_addextendedproperty N'MS_Description',N'安装时段表',N'user',N'dbo',N'table',N'[表名]',NULL,NULL
--删除表说明
--EXEC sp_dropextendedproperty N'MS_Description','user','dbo','table', '[表名]', NULL,NULL

--添加字段说明
EXECUTE sp_addextendedproperty N'MS_Description',N'【创建人】',N'user',N'dbo',N'table',N'[表名]',N'column',N'[字段名]'
EXECUTE sp_addextendedproperty N'MS_Description',N'【创建时间】',N'user',N'dbo',N'table',N'[表名]',N'column',N'[字段名]'
EXECUTE sp_addextendedproperty N'MS_Description',N'【修改人】',N'user',N'dbo',N'table',N'[表名]',N'column',N'[字段名]'
EXECUTE sp_addextendedproperty N'MS_Description',N'【修改时间】',N'user',N'dbo',N'table',N'[表名]',N'column',N'[字段名]'

--删除字段说明
--EXEC sp_dropextendedproperty N'MS_Description', 'user','dbo', 'table', '表名', 'column','字段名'

2、追加字段-删除字段
--添加字段
alter table [表名] ADD [字段名]INT NULL;
alter table [表名] ADD [字段名]nvarchar(50) NULL;

--添加字段说明
EXECUTE sp_addextendedproperty N'MS_Description',N'【项目名称】',N'user',N'dbo',N'table',[表名]',N'column',[字段名]';
EXECUTE sp_addextendedproperty N'MS_Description',N'【项目名称】',N'user',N'dbo',N'table',[表名]',N'column',[字段名]';

--删除字段
ALTER TABLE [表名] DROP COLUMN [字段名]
3、随机数
SELECT ltrim(floor(rand()*10000))
4、时间转字符串
--2018-11-13
SELECT CONVERT(varchar(50) , GETDATE(), 23 ) AS 'TIME'

--2018-11-13 18:46:14
SELECT CONVERT(varchar(50) , GETDATE(), 20 ) AS 'TIME'

--2019-01-14 17:15:59.920
select convert(varchar(50),GETDATE(),121)
5、查询年、月、日
SELECT

CONVERT (VARCHAR(4),YEAR(GETDATE())) AS '年',
CONVERT (VARCHAR(4),MONTH(GETDATE())) AS '月',
CONVERT (VARCHAR(4),DAY(GETDATE())) AS '日'

6、Case、When、Then
SELECT
CASE Sex
WHEN 0 THEN '女'
WHEN 1 THEN '男'
ELSE ''
END AS '性别'
FROM

[表名]

SELECT
CASE
WHEN w_grade >= 90 THEN'A'
WHEN w_grade >= 80 AND w_grade <= 89 THEN 'B'
WHEN w_grade >= 70 AND w_grade <= 79 THEN 'C'
WHEN w_grade >= 60 AND w_grade <= 69 THEN 'D'
ELSE 'E'
Swift代码www.gendan5.com/swiftcode.html

END AS '成绩评定'
FROM

[表名]

7、获取新增Sql的Id
SELECT @@IDENTITY --得到的是跨域最新id

SELECT IDENT_CURRENT('[表名]')--得到的是指定表的最新id

SELECT SCOPE_IDENTITY() --得到的是当前数据库中的最后插入表的id
8、增加序号
SELECT row_number () OVER (ORDER BY Id) AS '序号' ,* FROM [dbo].[表名]
9、Try-Catch
BEGIN TRY
SELECT 5 / 0
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE() AS '错误描述',

         ERROR_NUMBER() AS '错误号',
         ERROR_SEVERITY() AS '严重级别',
         ERROR_STATE() AS '错误状态号',
         ERROR_LINE() AS '出错的行号',
         ERROR_PROCEDURE() AS '发生错误的存储过程名或触发器名'

END CATCH
10、与时间相关的Sql查询
--20190306094000
select convert(varchar(8),GETDATE(),112)+replace(convert(varchar(8),GETDATE(),114),':','')

--20190306094332437
select convert(varchar(8),GETDATE(),112)+replace(convert(varchar(12),GETDATE(),14),':','')

--当月天数
select day(dateadd(ms,-3,DATEADD(m, DATEDIFF(m,0,getdate())+1,0)))

---当月第一天
select dateadd(d,-day(getdate())+1,getdate())

---当月最后一天
select dateadd(d,-day(getdate()),dateadd(m,1,getdate()))

--明年上月的最后一天此时
select dateadd(d,-day(getdate()),dateadd(m,12,getdate()))

--当月第一个星期一
SELECT DATEADD(wk, DATEDIFF(wk, '', DATEADD(dd, 6 - DAY(getdate()), getdate())), '')

--今天的所有数据
select * from [表名] where DateDiff(dd,CreateTime,getdate())=0

--昨天的所有数据
select * from [表名] where DateDiff(dd,CreateTime,getdate())=1

--7天内的所有数据
select * from [表名] where DateDiff(dd,CreateTime,getdate())<=7

--30天内的所有数据
select * from [表名] where DateDiff(dd,CreateTime,getdate())<=30

--本月的所有数据:
select * from [表名] where DateDiff(mm,CreateTime,getdate())=0

--本年的所有数据
select * from [表名] where DateDiff(yy,CreateTime,getdate())=0

--查询今天是今年的第几天
select datepart(dayofyear,getDate())

--查询今天是本月的第几天
select datepart(dd, getDate())
select day(getDate())

--查询本周的星期一日期是多少 (注意:指定日期不能是周日,如果是周日会计算到下周一去。所以如果是周日要减一天)
SELECT DATEADD(wk,DATEDIFF(wk,0,getdate()),0)

--查询昨天日期
select convert(char,dateadd(DD,-1,getdate()),121)

--查询本月第一天日期
Select DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) as firstday

--查询本月最后一天日期
Select dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0)) as lastday

--本月有多少天
select datepart(dd,dateadd(dd,-1,dateadd(mm,1,cast((cast(year(getdate()) as varchar)+'-'+cast(month(getdate()) as varchar)+'-01' ) as datetime ))))

--求两个时间段相差几天
select datediff(day,'2016/5/17','2016/8/20') as daysum

--在指定的日期上±N天
select convert(char,dateadd(dd,1,getdate()),111) as riqi

--在指定的日期上±N分钟://查询当前时间15分钟之前的日期
select dateadd(mi,-15,getdate())
11、查询sql执行时间和CPU占用时间和I/O操作情况
--查看执行时间和cpu占用时间

set statistics time on
select * from [表名]
set statistics time off

--查看查询对I/0的操作情况

set statistics io on
select * from [表名]
set statistics io off
12、替换
UPDATE [表名] SET [字段] = replace([字段], '替换前内容', '替换后内容');
13、删除表、清空表、复制表
DROP TABLE 表名称 --删除表
TRUNCATE TABLE 表名称 --清空表中的数据
select * into 目标表名 from 源表名
14、清理日志
USE [master]
GO
ALTER DATABASE 要清理的数据库名称 SET RECOVERY SIMPLE WITH NO_WAIT
GO
ALTER DATABASE 要清理的数据库名称 SET RECOVERY SIMPLE --简单模式
GO
USE 要清理的数据库名称
GO
DBCC SHRINKFILE (N'要清理的数据库名称_log' , 2, TRUNCATEONLY) --设置压缩后的日志大小为2M,可以自行指定
GO
USE [master]
GO
ALTER DATABASE 要清理的数据库名称 SET RECOVERY FULL WITH NO_WAIT
GO
ALTER DATABASE 要清理的数据库名称 SET RECOVERY FULL --还原为完全模式
GO
15、锁表查询、解锁
--查看被锁表:
SELECT
request_session_id spid,
OBJECT_NAME(resource_associated_entity_id) tableName
FROM
sys.dm_tran_locks
WHERE
resource_type = 'OBJECT'
ORDER BY request_session_id ASC

-- 解锁:
DECLARE @spid INT
SET @spid = 52 --锁表进程
DECLARE @SQL VARCHAR (1000)
SET @SQL = 'kill ' + CAST (@spid AS VARCHAR)
EXEC (@SQL)
16、Sql语句性能Top10 
SELECT TOP 10
st.text AS [父级完整语句],
SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,((CASE statement_end_offset WHEN -1 THEN DATALENGTH(st.text) ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) + 1) as [统计对应的部分语句],
CAST( ((qs.total_elapsed_time / 1000000.0)/qs.execution_count) AS DECIMAL(28,2) ) AS [平均消耗秒数],
CAST(qs.last_elapsed_time / 1000000.0 AS DECIMAL(28, 2)) AS [最后完成消耗秒数],
qs.last_execution_time AS [最后执行时间],
CAST(qs.min_elapsed_time / 1000000.0 AS DECIMAL(28, 2)) AS [最小消耗秒数],
CAST(qs.max_elapsed_time / 1000000.0 AS DECIMAL(28, 2)) AS [最大消耗秒数],
CAST(qs.total_elapsed_time / 1000000.0 AS DECIMAL(28, 2)) AS [总消耗秒数],
(qs.execution_count) AS [总执行次数],
creation_time AS [编译计划的时间],
CAST(qs.last_worker_time / 1000000.0 AS DECIMAL(28, 2)) AS [最后完成占用CPU秒数]
from sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
WHERE qs.last_execution_time>DATEADD(n,-30,GETDATE())
ORDER BY qs.last_worker_time DESC
17、查询 表信息
SELECT
表名=case when a.colorder=1 then d.name else '' end,
表说明=case when a.colorder=1 then isnull(f.value,'') else '' end,
字段序号=a.colorder,
字段名=a.name,
标识=case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' end,
主键=case when exists(SELECT 1 FROM sysobjects where xtype='PK' and name in (
SELECT name FROM sysindexes WHERE indid in(
SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid
))) then '√' else '' end,
类型=b.name,
占用字节数=a.length,
长度=COLUMNPROPERTY(a.id,a.name,'PRECISION'),
小数位数=isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0),
允许空=case when a.isnullable=1 then '√'else '' end,
默认值=isnull(e.text,''),
字段说明=isnull(g.[value],'')
FROM syscolumns a
left join systypes b on a.xusertype=b.xusertype
inner join sysobjects d on a.id=d.id and d.xtype='U' and d.name<>'dtproperties'
left join syscomments e on a.cdefault=e.id
left join sys.extended_properties g on a.id=g.major_id and a.colid=g.minor_id
left join sys.extended_properties f on d.id=f.major_id and f.minor_id=0
--where d.name='[表名]' --如果只查询指定表,加上此条件
order by a.id,a.colorder
18、查询表说明

SELECT

表名 = d.name,
表说明 = isnull(f. VALUE, ''),

表查询 = 'SELECT TOP 10 * FROM ' +d.name+';',
表说明 = '--' + CONVERT(varchar(100),isnull(f. VALUE, ''))
FROM

sysobjects d

LEFT JOIN sys.extended_properties f ON d.id = f.major_id
AND f.minor_id = 0
WHERE

d.xtype = 'U'

AND d.name <> 'dtproperties'
--and d.Name like '%[表名]%' --如果只查询指定表,加上此条件
ORDER BY d.name
19、查询表字段详情
SELECT
表名=case when a.colorder=1 then d.name else '' end,
表说明=case when a.colorder=1 then isnull(f.value,'') else '' end,
字段名1=a.name,
字段名5=(SELECT STUFF((SELECT ',' + a.Name FROM syscolumns AS a INNER JOIN sysobjects d ON a.id = d.id AND d.xtype = 'U' AND d.name <> 'dtproperties' where d.name='[表名]' FOR XML PATH ('')),1,1,'')),
字段名6=(SELECT STUFF((SELECT ',@' + a.Name FROM syscolumns AS a INNER JOIN sysobjects d ON a.id = d.id AND d.xtype = 'U' AND d.name <> 'dtproperties' where d.name='[表名]' FOR XML PATH ('')),1,1,'')),
字段名7=(SELECT STUFF((SELECT ','+ CASE

WHEN b.name = 'nvarchar' THEN 'string'
WHEN b.name = 'int' THEN 'int'
WHEN b.name = 'datetime' THEN 'DateTime'
ELSE 'decimal?'

END +' ' + a.Name FROM syscolumns AS a left join systypes b on a.xusertype=b.xusertype inner join sysobjects d on a.id=d.id and d.xtype='U' and d.name<>'dtproperties' where d.name='[表名]' FOR XML PATH ('')),1,1,'')),
字段名8='new SqlParameter("@'+a.name+'", '+a.name+'),',
字段名9=case

    when b.name = 'nvarchar' then '/// 
    ///'+ isnull(CONVERT(varchar(100),g.[value]),'')+'
    /// 
            public string '+a.name+' { get; set; }'
          when b.name = 'int' then'/// 
    /// '+ isnull(CONVERT(varchar(100),g.[value]),'')+'
    /// 
            public int '+a.name+' { get; set; }'
            when b.name = 'datetime' then'/// 
    /// '+ isnull(CONVERT(varchar(100),g.[value]),'')+'
    /// 
            public DateTime '+a.name+' { get; set; }'
            else '/// 
    /// '+ isnull(CONVERT(varchar(100),g.[value]),'')+'
    /// 
            public decimal? '+a.name+' { get; set; }' end,

类型 = case when b.name = 'nvarchar' then b.name +'('+ CONVERT(varchar(50),COLUMNPROPERTY(a.id,a.name,'PRECISION'))+'),' else b.name+',' end,
字段说明1= case when (isnull(CONVERT(varchar(100),g.[value]),'')) ='' then '' else ('--' + isnull(CONVERT(varchar(100),g.[value]),'')) end,
字段说明2= case when (isnull(CONVERT(varchar(100),g.[value]),'')) ='' then '' else ('/' + isnull(CONVERT(varchar(100),g.[value]),'') + '/') end,
字段说明3= case when (isnull(CONVERT(varchar(100),g.[value]),'')) ='' then '' else ('//' + isnull(CONVERT(varchar(100),g.[value]),'')) end
FROM syscolumns a
left join systypes b on a.xusertype=b.xusertype
inner join sysobjects d on a.id=d.id and d.xtype='U' and d.name<>'dtproperties'
left join syscomments e on a.cdefault=e.id
left join sys.extended_properties g on a.id=g.major_id and a.colid=g.minor_id
left join sys.extended_properties f on d.id=f.major_id and f.minor_id=0
where d.name='[表名]'
order by a.id,a.colorder

你可能感兴趣的:(sql语句)