表操作
-
查表大小
sp_spaceused 表名
-
修改表名
ALTER TABLE table RENAME TO NEW_TABLE_NAME;
-
修改列名
不支持ALTER TABLE table RENAME COLUMN OLD_COLUMN_NAME TO NEW_COLUMN_NAME
支持以下两种方式
sp_rename 'change.Times','TIMES1','column' go -- 或者 EXEC sp_rename 'T_WeiBoHot.citme','ctime','column' go -- change是表名,times是原来的列名,times1是新的列名
-
修改列的数据类型
ALTER TABLE dbo.T_Intervene_HistoryDBRate ALTER COLUMN rate REAL;
-
插入/删除列
ALTER TABLE table ADD COLUMN_NAME DATATYPE; go ALTER TABLE table DROP COLUMN COLUMN_NAME;
-
分区
建分区CREATE PARTITION FUNCTION [fq_function](tinyint) AS RANGE LEFT FOR VALUES (0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07) GO CREATE PARTITION SCHEME [fq_Scheme] AS PARTITION [fq_function] TO ([PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY], [PRIMARY]) GO
查询某分区数据
SELECT * FROM dbo.T_monnewssource_FQTest WITH(NOLOCK) WHERE $PARTITION.fq31_function(fq_date) = 30;
查当天数据所在分区
SELECT $PARTITION.fq31_function(datediff(day,'2015-07-01',getdate())%31);
分区依据
fq_date TINYINT DEFAULT (datediff(day,'2015-01-01',getdate())%(8)) -- 分区依据字段值从0~7,分区从1~8 -- 31个分区时,只保留7个分区 DECLARE @i TINYINT = 1,@j TINYINT = 25,@str VARCHAR(100) = ''; WHILE @i < 25 BEGIN SELECT @i = @i + 1; SELECT @str = @str + ',' + LTRIM(@j); IF @j = 31 BEGIN SELECT @j = 0 END SELECT @j = @j + 1; END SELECT STUFF(@str,1,1,'') AS strs;
过程,作业和触发器等操作
-
触发器
禁用触发器:
ALTER TABLE trig_example DISABLE TRIGGER trig1
恢复触发器:
ALTER TABLE trig_example ENABLE TRIGGER trig1
禁用某个表上的所有触发器
ALTER TABLE 你的表 DISABLE TRIGGER all
启用某个表上的所有触发器
ALTER TABLE 你的表 enable TRIGGER all
禁用所有表上的所有触发器
exec sp_msforeachtable 'ALTER TABLE ? DISABLE TRIGGER all'
启用所有表上的所有触发器
exec sp_msforeachtable 'ALTER TABLE ? enable TRIGGER all'
-
查询作业
select a.name,b.command from msdb.dbo.sysjobs a inner join msdb.dbo.sysjobsteps b on a.job_id = b.job_id where b.command like '%P_GZ_HeavyPaste_UpOrder%'; `
-
查询过程
select a.name,b.text from sys.objects a inner join sys.syscomments b on a.object_id = b.id where a.type = 'P' and b.text like '%T_SEM_PostSnap%';
-
查询触发器
SELECT * FROM sys.objects WHERE type = 'tr';
-
查询视图
select * from sysobjects where xtype='V';
-
查看进程
SELECT PRO.spid ,DB_NAME(PRO.dbid) AS DBName ,PRO.program_name ,waitresource ,PRO.loginame AS LoginName ,DB.name AS DatabaseName ,PRO.[status] as ProcessStatus ,PRO.cmd AS Command ,PRO.last_batch AS LastBatch ,PRO.cpu AS Cpu ,PRO.physical_io AS PhysicalIo ,PRO.hostname ,SES.row_count AS [RowCount] ,STM.[text] AS SQLStatement FROM sys.sysprocesses AS PRO INNER JOIN sys.databases AS DB ON PRO.dbid = DB.database_id INNER JOIN sys.dm_exec_sessions AS SES ON PRO.spid = SES.session_id CROSS APPLY sys.dm_exec_sql_text(PRO.sql_handle) AS STM WHERE PRO.spid >= 50 -- Exclude system processes ORDER BY PRO.physical_io DESC ,PRO.cpu DESC go SELECT * FROM sys.sysprocesses AS pro CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sql WHERE pro.spid = 135
-
循环执行过程
DECLARE @i INT =1 WHILE @i=1 BEGIN EXEC @i=P_wenda_ExportQuestionDaily; --过程return 1 END
-
查看过程执行情况
SELECT ISNULL(DBS.name, '') AS DatabaseName ,OBJECT_NAME(EPS.object_id, EPS.database_id) AS ObjectName ,EPS.cached_time AS CachedTime ,EPS.last_elapsed_time AS LastElapsedTime ,EPS.execution_count AS ExecutionCount ,EPS.total_worker_time / EPS.execution_count AS AvgWorkerTime ,EPS.total_elapsed_time / EPS.execution_count AS AvgElapsedTime ,(EPS.total_logical_reads + EPS.total_logical_writes) / EPS.execution_count AS AvgLogicalIO FROM sys.dm_exec_procedure_stats AS EPS LEFT JOIN sys.databases AS DBS ON EPS.database_id = DBS.database_id ORDER BY AvgWorkerTime DESC;
-
查看开销较大过程
SELECT ss.SUM_execution_count , t.text , ss.SUM_total_elapsed_time , ss.sum_total_worker_time , ss.sum_total_logical_reads , ss.sum_total_logical_writes FROM ( SELECT S.plan_handle , SUM(s.execution_count) SUM_Execution_count , SUM(s.total_elapsed_time) SUM_total_elapsed_time , SUM(s.total_worker_time) SUM_total_worker_time , SUM(s.total_logical_reads) SUM_total_logical_reads , SUM(s.total_logical_writes) SUM_total_logical_writes FROM sys.dm_exec_query_stats s GROUP BY S.plan_handle ) AS ss CROSS APPLY sys.dm_exec_sql_text(ss.plan_handle) t ORDER BY sum_total_logical_reads DESC
连接
-
full join
SELECT (CASE WHEN A.customerId IS NULL THEN B.customerId ELSE A.customerId END) AS customerId, A.itemMoney AS currentNum, B.itemMoney AS frontNum INTO #W FROM #CA AS A FULL JOIN (SELECT customerId, itemMoney FROM #CA WHERE customerType = 2) AS B ON A.customerId = B.customerId WHERE A.customerType = 1 go SELECT (CASE WHEN W.customerId IS NULL THEN C.customerId ELSE W.customerId END) AS customerId, W.currentNum, W.frontNum, C.itemMoney AS lastYearNum INTO #WW FROM #W AS W FULL JOIN (SELECT customerId, itemMoney FROM #CA WHERE customerType = 3) AS C ON W.customerId = C.customerId go
-
cross apply
SELECT F.usergroupid, F.row, S.Element FROM dbo.T_Cabin_FeatureWords AS F CROSS APPLY dbo.ufn_split(row, '-') AS S WHERE usergroupid = 21
-
merge
MERGE dbo.T_I8_CommentGroup AS A USING (SELECT @e_id AS id) AS B ON A.ug_id = B.id WHEN MATCHED THEN UPDATE SET ug_useflag = @ug_useflag, os_depict = @os_depict WHEN NOT MATCHED THEN INSERT (ug_id, ug_useflag, os_depict, lasttime) VALUES (@e_id, @ug_useflag, @os_depict, CONVERT(VARCHAR(10), GETDATE() - 7, 121)) go MERGE dbo.T_I8_CommentUserGroup AS A USING ( SELECT @e_id AS id, B.col FROM dbo.f_split(@ug_ids,',') AS B WHERE B.col > '' )AS C ON A.e_id = C.id AND A.ug_id = CONVERT(INT, C.col) WHEN NOT MATCHED THEN INSERT (e_id, ug_id) VALUES (C.id, C.col) WHEN NOT MATCHED BY SOURCE AND A.e_id = @e_id THEN DELETE go
索引
-
创建唯一索引并忽略重复值(已有的)
CREATE UNIQUE INDEX idx_temp_id ON dbo.temp_lxc (id) WITH(IGNORE_DUP_KEY = ON);
-
删除索引语句
DROP INDEX sy ON salary;
- 指定使用某索引
SELECT 字段名表 FROM 表名表 WITH (INDEX(索引名)) WHERE 查询条件;
-
建全文索引
开启全文索引execute sp_fulltext_database 'enable';
定义全文索引目录(fulltext_bbsBoard_PostDay)
EXEC [sys].[sp_fulltext_catalog] @ftcat = 'fulltext_bbsBoard_PostDay', -- sysname @action = 'create', -- varchar(20) @path = N'D:\fulltext' -- nvarchar(101)
为表[T_bbsBoard_PostDay]创建全文索引 可索引列为 id
EXEC [sys].[sp_fulltext_table] @tabname = N'T_bbsBoard_PostDay', -- nvarchar(517) @action = 'create', -- varchar(50) @ftcat = fulltext_bbsBoard_PostDay, -- sysname @keyname = PK__T_bbsBoa__521F78666482D9EB -- sysname
设置全文索引列名
EXEC [sys].[sp_fulltext_column] @tabname = N'T_bbsBoard_PostDay', -- nvarchar(517) @colname = title, -- sysname @action = 'add', -- varchar(20) @language = 2052 -- int 2057 is the LCID for 英语 1033 :美语 2052:中文
激活索引
EXEC [sys].[sp_fulltext_table] @tabname = N'T_bbsBoard_PostDay', -- nvarchar(517) @action = 'activate'
填充索引,首次创建完全文索引之后先完全填充索引,把数据全部放入全文索引里
ALTER FULLTEXT INDEX ON dbo.T_bbsBoard_PostDay SET CHANGE_TRACKING OFF GO ALTER FULLTEXT INDEX ON dbo.T_bbsBoard_PostDay START FULL POPULATION GO
修改填充方式为自动跟踪更改,等数据有变化的时候只需要把变化的部分填充进去全文索引里
ALTER FULLTEXT INDEX ON dbo.T_bbsBoard_PostDay SET CHANGE_TRACKING AUTO GO
- 使用全文索引
WHERE CONTAINS(Title,'华为 and/or 联想')
约束
-
建唯一约束
ALTER TABLE T_WenDa_QuestionZFM ADD CONSTRAINT un_QuestionZFM_autoid UNIQUE(autoid); go ALTER TABLE dbo.T_MS_TopicBlackList ADD CONSTRAINT pk_TopicBlackList_topicid PRIMARY KEY (topic_id);
-
删约束
ALTER TABLE dbo.T_SEM_TriLo DROP CONSTRAINT DF__T_SEM_Tri__ji_fl__4262CC11;
-
为已有列添加默认值
ALTER TABLE dbo.T_SEM_ShowJsonShotSnap ADD CONSTRAINT ShowJsonShotSnap_defualt_rgNum DEFAULT(0) FOR rgNum;
时间日期处理
-
显示年月日部分:
convert(nvarchar(10), date1, 21)
-
取得该月第一天:
DATEADD(DD, -DAY(GETDATE()) + 1, GETDATE())
-
取得该月最后一天:
DATEADD(DD, -DAY(GETDATE()), DATEADD(MM, 1, GETDATE()))
算法
-
返回插入到标识列中的值(SCOPE_IDENTITY/IDENT_CURRENT/@@IDENTITY)
返回插入数据条数使用 @@ROWCOUNTCREATE TABLE #A(id INT); INSERT INTO dbo.tongxuelu ( t_name, t_sex, t_age ) OUTPUT INSERTED.t_id INTO #A SELECT 'abc','女',0;
-
遍历
; WITH SUB(id, fid, word, paths,layer,word_id) AS ( SELECT C.cls_id,C.cls_fid,C.cls_path_word,C.cls_path_wordstr,C.cls_layer,C.cls_path_id FROM QADATA.dbo.T_QA_Class AS C WITH(NOLOCK) WHERE C.cls_id = 868163 UNION ALL SELECT C.cls_id,C.cls_fid,C.cls_path_word,C.cls_path_wordstr,C.cls_layer,C.cls_path_id FROM SUB AS S INNER JOIN QADATA.dbo.T_QA_Class AS C WITH(NOLOCK) ON S.id = C.cls_fid ) SELECT * FROM SUB ORDER BY layer ASC;
- 随机函数
NEWID()
-
组内排序
ROW_NUMBER() OVER(PARTITION BY A.Url ORDER BY A.Utime DESC) AS n
-
哈希排重(MD5)
SELECT CONVERT(UNIQUEIDENTIFIER,HASHBYTES('MD5','LXC')); SELECT @titlehash = CONVERT(UNIQUEIDENTIFIER,HASHBYTES('md5', SUBSTRING( ISNULL(@title, ''),1,255))); contenthash = CONVERT(UNIQUEIDENTIFIER , HASHBYTES('md5',LEFT(RTRIM(LTRIM(@content)),4000))
-
拼接字符串
SELECT t_type + ',' FROM #toolList FOR XML PATH(''); go CREATE TABLE #words(id INT,word NVARCHAR(8)); INSERT INTO #words( id,word ) SELECT 1,'过去' UNION SELECT 1,'现在' UNION SELECT 1,'将来' UNION SELECT 2,'过去2' UNION SELECT 3,'现在3' UNION SELECT 2,'将来2' SELECT * FROM #words; DECLARE @a NVARCHAR(max); SELECT @a = STUFF((SELECT '|' + word FROM #words FOR XML PATH('')),1,1,''); SELECT @a; go SELECT B.id,STUFF((SELECT '|' + word FROM #words AS A WHERE A.id = B.id FOR XML PATH('')),1,1,'') FROM #words AS B GROUP BY B.id DROP TABLE #words; CREATE TABLE #temp(id INT); INSERT INTO #temp ( id ) SELECT 1 UNION SELECT 2 UNION SELECT 3; SELECT STUFF((SELECT ',' + LTRIM(id) FROM #temp FOR XML PATH('')),1,1,''); DROP TABLE #temp;
-
平均分配(个数/时间)
CREATE TABLE #temp(id INT,iname VARCHAR(10)); INSERT INTO #temp( id, iname ) SELECT 1,'a' UNION SELECT 2,'b' UNION SELECT 3,'c' SELECT * FROM #temp; SELECT * FROM #temp AS t,dbo.Nums AS n WHERE n.n <= CEILING(10*1.0/3); DECLARE @endTime DATETIME = GETDATE() + 1; SELECT *,DATEADD(MINUTE,(id-1) * DATEDIFF(MINUTE,GETDATE(),@endTime) / 4,GETDATE()) FROM #temp
-
计算某词在串中出现个数
DECLARE @str VARCHAR(100)= 'a,b,c,d' SELECT @str SELECT LEN(@str) - LEN(REPLACE(@str, 'a', ''))
-
构造日期表
SELECT CAST(GETDATE()-number AS DATE) AS time FROM master..spt_values WHERE type='P' AND number<30
-
构造递增表
SELECT number FROM master..spt_values WHERE type = 'P' AND number < 24
-
判断字符串是否是纯数字或字母
-- 纯数字: ISNUMERIC(title) = 1 -- 纯数字: PATINDEX('%[^0-9]%','12324') = 0 -- 纯英文: PATINDEX('%[^a-z]%','abc') = 0 --- 不含汉字和字母: PATINDEX('%[吖-咗a-zA-Z]%',Title) = 0 -- 不含汉字: PATINDEX('%[吖-咗]%',title) = 0
-
正则表达式
获取字符串中的英文字符
declare @str varchar(100) set @str='xyz123z5' select dbo.regexReplace(@str,'[^a-zA-Z]','',1,1)
获取字符串中的英文字符长度
declare @str varchar(100) set @str='xyz123z5' select len(dbo.regexReplace(@str,'[^a-zA-Z]','',1,1))
语句块例子:
create function dbo.regexReplace ( @source varchar(5000), --原字符串 @regexp varchar(1000), --正则表达式 @replace varchar(1000), --替换值 @globalReplace bit = 0, --是否是全局替换 @ignoreCase bit = 0 --是否忽略大小写 ) returnS varchar(1000) AS begin declare @hr integer declare @objRegExp integer declare @result varchar(5000) exec @hr = sp_OACreate 'VBScript.RegExp', @objRegExp OUTPUT IF @hr <> 0 begin exec @hr = sp_OADestroy @objRegExp return null end exec @hr = sp_OASetProperty @objRegExp, 'Pattern', @regexp IF @hr <> 0 begin exec @hr = sp_OADestroy @objRegExp return null end exec @hr = sp_OASetProperty @objRegExp, 'Global', @globalReplace IF @hr <> 0 begin exec @hr = sp_OADestroy @objRegExp return null end exec @hr = sp_OASetProperty @objRegExp, 'IgnoreCase', @ignoreCase IF @hr <> 0 begin exec @hr = sp_OADestroy @objRegExp return null end exec @hr = sp_OAMethod @objRegExp, 'Replace', @result OUTPUT, @source, @replace IF @hr <> 0 begin exec @hr = sp_OADestroy @objRegExp return null end exec @hr = sp_OADestroy @objRegExp IF @hr <> 0 begin return null end return @result end GO
其他
-
创建数据库
create database stuDB on primary -- 默认就属于primary文件组,可省略 ( /*--数据文件的具体描述--*/ name='stuDB_data', -- 主数据文件的逻辑名称 filename='D:\stuDB_data.mdf', -- 主数据文件的物理名称 size=5mb, --主数据文件的初始大小 maxsize=100mb, -- 主数据文件增长的最大值,不限制的话可用“unlimited” filegrowth=15%--主数据文件的增长率,也可指定大小 ) log on ( /*--日志文件的具体描述,各参数含义同上--*/ name='stuDB_log', filename='D:\stuDB_log.ldf', size=2mb, filegrowth=1mb --也可用增长率 )
一个数据库中,只可以有一个 主数据文件(扩展名: .mdf),多个次数据文件(扩展名: .ndf),多个日志文件(扩展名: .Ldf);
多文件及文件组示例:
CREATE DATABASE Sales ON PRIMARY ( NAME = SPri1_dat, FILENAME = 'D:\SalesData\SPri1dat.mdf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 15% ), ( NAME = SPri2_dat, FILENAME = 'D:\SalesData\SPri2dt.ndf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 15% ), FILEGROUP SalesGroup1 ( NAME = SGrp1Fi1_dat, FILENAME = 'D:\SalesData\SG1Fi1dt.ndf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ), ( NAME = SGrp1Fi2_dat, FILENAME = 'D:\SalesData\SG1Fi2dt.ndf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ), FILEGROUP SalesGroup2 ( NAME = SGrp2Fi1_dat, FILENAME = 'D:\SalesData\SG2Fi1dt.ndf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ), ( NAME = SGrp2Fi2_dat, FILENAME = 'D:\SalesData\SG2Fi2dt.ndf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) LOG ON ( NAME = Sales_log, FILENAME = 'E:\SalesLog\salelog.ldf', SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB ) ; GO
-
关闭/开启 Transact-SQL 语句或存储过程影响的行计数的消息
SET NOCOUNT ON go SET NOCOUNT OFF go SET NOCOUNT ON
- 符号
回车符:char(13)
换行符:char(10)
制表符: CHAR(9) -
开启/关闭自增列
显示值插入(修改会话中的IDENTITY_INSERT ),临时性 ,不彻底改表列性质SET IDENTITY_INSERT [ database_name . [ schema_name ] . ] table { ON | OFF }
-
查服务器名
SELECT @@SERVERNAME;
-
页面无法执行过程时,环境设置
SET ANSI_WARNINGS ON; SET ANSI_PADDING ON; SET CONCAT_NULL_YIELDS_NULL ON;
-
锁
查死锁select request_session_id spid,OBJECT_NAME(resource_associated_entity_id) tableName from sys.dm_tran_locks where resource_type='OBJECT' AND OBJECT_NAME(resource_associated_entity_id) = 'MonNews_floors_ContentText'; select request_session_id spid,OBJECT_NAME(resource_associated_entity_id) tableName from sys.dm_tran_locks where resource_type='OBJECT'; select top 100* from master..sysprocesses a cross apply sys.dm_exec_sql_text(a.sql_handle) b where a.spid>50 AND b.text LIKE '%T_bbsBoard_PostDay%' order by hostname; select request_session_id spid,OBJECT_NAME(resource_associated_entity_id) tableName from sys.dm_tran_locks where resource_type='OBJECT;
解锁
declare @spid int Set @spid = 57 --锁表进程 declare @sql varchar(1000) set @sql='kill '+cast(@spid as varchar) exec(@sql)
检索死锁进程
select spid, blocked, loginame, last_batch, status, cmd, hostname, program_name from sysprocesses where spid in (select blocked from sysprocesses where blocked <> 0 ) or (blocked <>0)
-
表A数据量很大,现需要保留表A的少量数据
删除A耗时长而且会增加数据库负载,可以考虑更换表名的方法达到目的
假设表A有自增id1).新建与表 A 结构相同的表 B;
2).停止表 A 的作业修改过程 让表A数据不再变化;
3).将 表 A 要保留数据 指定相同自增id 插入 表 B;SET IDENTITY_INSERT B ON INSERT B SELECT ... FROM A WHERE ... SET IDENTITY_INSERT B OFF
4).指定 表 B 自增id;
查询 表 A 自增id当前值DBCC CHECKIDENT (A)
;
指定表 B 为 与 表 A 一样的新值DBCC CHECKIDENT (B, RESEED, value)
;
5).重命名的方式到达 备份删除目的;EXEC sp_rename A,A1 EXEC sp_rename B,A
-
查询相邻两条记录间的数据增加或减少值
通过查询原来的数据库,建立两个临时表。临时表中添加一个字段作为顺序标签。
第一个临时表中顺序标签是0开始,第二个临时表从1开始。然后两个表直接通过顺序标签这一列进行内联,这样不就能直接计算增量值了啊。在查询的时候还能直接把其他相关的时间等信息都带出来。注意,这样是让两个表格对应错位,以便求增量,所以两个临时表中都有一行在内联中丢失掉。