一、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