SQL SERVER 月、季、年统计与常用查询语句汇总
@@sqlserver 年 季 月
SQL SERVER 月、季、年统计与常用查询语句汇总
一、SQL SERVER 月、季、年统计查询
--本天
SELECT *FROM dbo.TableName WHERE DATEDIFF(DAY,TimeField,getdate())= 0;
--本周
SELECT *FROM dbo.TableName WHERE DATEDIFF(WEEK,TimeField,getdate())= 0;
--本月
SELECT *FROM dbo.TableName WHERE DATEDIFF(MONTH,TimeField,getdate())= 0;
--本季度
SELECT *FROM dbo.TableName WHERE DATEPART(qq, TimeField) = DATEPART(qq, GETDATE()) and DATEPART(yy, TimeField) = DATEPART(yy, GETDATE());
--本年
SELECT *FROM dbo.TableName where DATEDIFF(YEAR, TimeField,getdate())= 0;
注:TableName为查询的表名,TimeFiled为查询的时间字段
二、SQL SERVER 判断表、字段、存储过程、触发器是否存在
--判断表是否存在
SELECT *FROM sys.objects WHERE OBJECT_ID = OBJECT_ID('表名') AND OBJECTPROPERTY(object_id, N'IsUserTable') = 1
--或
SELECT *FROM sys.objects WHERE OBJECT_ID = OBJECT_ID('表名') AND type='u'
--判断字段是否存在
SELECT *FROM sys.columns WHERE OBJECT_ID = OBJECT_ID('字段名') AND Name = 'No'
--判断存储过程是否存在
SELECT *FROM sys.objects WHERE OBJECT_ID = OBJECT_ID('存储过程名') AND
OBJECTPROPERTY(object_id, N'IsProcedure') = 1
--或
SELECT *FROM sys.objects WHERE OBJECT_ID = OBJECT_ID('存储过程名') AND type='p'
--判断触发器是否存在
SELECT *FROM sys.objects WHERE OBJECT_ID = OBJECT_ID('触发器名') AND OBJECTPROPERTY(object_id, N'IsTrigger') = 1
--或
SELECT *FROM sys.objects WHERE OBJECT_ID = OBJECT_ID('触发器名') AND type='TR'
三 、表复制语句
-- 要求表2不存在,查询时自动创建
Select Field1,Field2 from Table1 Into Table2
--要求表2必须存在,可以插入常量
Insert into table2 (Field1,Field2) select Field1,Field2 from table1
四、关联更新
UPDATE Table1 SET T1F1 = T2F1, T1F2 = T2F2, T1F3 = T2F3 FROM Table1, Table2 WHERE Table1.Key = Table2.Key
-----------------------------------
SQL SERVER 月、季、年统计与常用查询语句汇总
https://blog.51cto.com/u_15127636/3865298