T-SQL(http://www.cnblogs.com/ghd258/archive/2006/03/20/354147.html)

把长日期转换为短日期 Convert(char(10),getdate(),120)
None.gif MS-SQL数据库开发常用汇总 1.按姓氏笔画排序:
None.gifSelect * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as
None.gif2.数据库加密:
None.gifselect encrypt('原始密码')
None.gifselect pwdencrypt('原始密码')
None.gifselect pwdcompare('原始密码','加密后密码') = 1--相同;否则不相同 encrypt('原始密码')
None.gifselect pwdencrypt('原始密码')
None.gifselect pwdcompare('原始密码','加密后密码') = 1--相同;否则不相同
None.gif3.取回表中字段:
None.gifdeclare @list varchar(1000),@sql nvarchar(1000)
None.gifselect @list=@list+','+b.name from sysobjects a,syscolumns b where a.id=b.id and a.name='表A'
None.gifset @sql='select '+right(@list,len(@list)-1)+' from 表A'
None.gifexec (@sql)
None.gif4.查看硬盘分区:
None.gifEXEC master..xp_fixeddrives
None.gif5.比较A,B表是否相等:
None.gifif (select checksum_agg(binary_checksum(*)) from A)
None.gif=
None.gif(select checksum_agg(binary_checksum(*)) from B)
None.gifprint '相等'
None.gifelse
None.gifprint '不相等'
None.gif6.杀掉所有的事件探察器进程:
None.gifDECLARE hcforeach CURSOR GLOBAL FOR SELECT 'kill '+RTRIM(spid) FROM master.dbo.sysprocesses
None.gifWHERE program_name IN('SQL profiler',N'SQL 事件探查器')
None.gifEXEC sp_msforeach_worker '?'
None.gif7.记录搜索:
None.gif开头到N条记录
None.gifSelect Top N * From 表
None.gif-------------------------------
None.gifN到M条记录(要有主索引ID)
None.gifSelect Top M-N * From 表 Where ID in (Select Top M ID From 表) Order by ID Desc
None.gif----------------------------------
None.gifN到结尾记录
None.gifSelect Top N * From 表 Order by ID Desc
None.gif8.如何修改数据库的名称:
None.gifsp_renamedb 'old_name', 'new_name'
None.gif9:获取当前数据库中的所有用户表
None.gifselect Name from sysobjects where xtype='u' and status>=0
None.gif10:获取某一个表的所有字段
None.gifselect name from syscolumns where id=object_id('表名')
None.gif11:查看与某一个表相关的视图、存储过程、函数
None.gifselect a.* from sysobjects a, syscomments b where a.id = b.id and b.text like '%表名%'
None.gif12:查看当前数据库中所有存储过程
None.gifselect name as 存储过程名称 from sysobjects where xtype='P'
None.gif13:查询用户创建的所有数据库
None.gifselect * from master..sysdatabases D where sid not in(select sid from master..syslogins where name='sa')
None.gif或者
None.gifselect dbid, name AS DB_NAME from master..sysdatabases where sid <> 0x01
None.gif14:查询某一个表的字段和数据类型
None.gifselect column_name,data_type from information_schema.columns
None.gifwhere table_name = '表名'
None.gif[n].[标题]:
None.gifSelect * From TableName Order By CustomerName
None.gif[n].[标题]:
None.gif
来自 http://dev.csdn.net/develop/article/83/83138.shtm

一、 只复制一个表结构,不复制数据

None.gifselect top 0 * into [t1] from [t2]


二、 获取数据库中某个对象的创建脚本

1、 先用下面的脚本创建一个函数

None.gifif exists(select 1 from sysobjects where id=object_id('fgetscript') and objectproperty(id,'IsInlineFunction')=0)
None.gif drop function fgetscript
None.gifgo
None.gif
None.gifcreate function fgetscript(
None.gif @servername varchar(50) --服务器名
None.gif ,@userid varchar(50)='sa' --用户名,如果为nt验证方式,则为空
None.gif ,@password varchar(50)='' --密码
None.gif ,@databasename varchar(50) --数据库名称
None.gif ,@objectname varchar(250) --对象名
None.gif
None.gif) returns varchar(8000)
None.gifas
None.gifbegin
None.gif declare @re varchar(8000) --返回脚本
None.gif declare @srvid int,@dbsid int --定义服务器、数据库集id
None.gif declare @dbid int,@tbid int --数据库、表id
None.gif declare @err int,@src varchar(255), @desc varchar(255) --错误处理变量
None.gif
None.gif--创建sqldmo对象
None.gif exec @err=sp_oacreate 'sqldmo.sqlserver',@srvid output
None.gif if @err<>0 goto lberr
None.gif
None.gif--连接服务器
None.gif if isnull(@userid,'')='' --如果是 Nt验证方式
None.gif begin
None.gif exec @err=sp_oasetproperty @srvid,'loginsecure',1
None.gif if @err<>0 goto lberr
None.gif
None.gif exec @err=sp_oamethod @srvid,'connect',null,@servername
None.gif end
None.gif else
None.gif exec @err=sp_oamethod @srvid,'connect',null,@servername,@userid,@password
None.gif
None.gif if @err<>0 goto lberr
None.gif
None.gif--获取数据库集
None.gif exec @err=sp_oagetproperty @srvid,'databases',@dbsid output
None.gif if @err<>0 goto lberr
None.gif
None.gif--获取要取得脚本的数据库id
None.gif exec @err=sp_oamethod @dbsid,'item',@dbid output,@databasename
None.gif if @err<>0 goto lberr
None.gif
None.gif--获取要取得脚本的对象id
None.gif exec @err=sp_oamethod @dbid,'getobjectbyname',@tbid output,@objectname
None.gif if @err<>0 goto lberr
None.gif
None.gif--取得脚本
None.gif exec @err=sp_oamethod @tbid,'script',@re output
None.gif if @err<>0 goto lberr
None.gif
None.gif --print @re
None.gif return(@re)
None.gif
None.giflberr:
None.gif exec sp_oageterrorinfo NULL, @src out, @desc out
None.gif declare @errb varbinary(4)
None.gif set @errb=cast(@err as varbinary(4))
None.gif exec master..xp_varbintohexstr @errb,@re out
None.gif set @re='错误号: '+@re
None.gif +char(13)+'错误源: '+@src
None.gif +char(13)+'错误描述: '+@desc
None.gif return(@re)
None.gifend
None.gifgo
None.gif
None.gif

2、 用法如下
用法如下,

None.gifprint dbo.fgetscript('服务器名','用户名','密码','数据库名','表名或其它对象名')
None.gif

3、 如果要获取库里所有对象的脚本,如如下方式

None.gifdeclare @name varchar(250)
None.gifdeclare #aa cursor for
None.gif select name from sysobjects where xtype not in('S','PK','D','X','L')
None.gifopen #aa
None.giffetch next from #aa into @name
None.gifwhile @@fetch_status=0
None.gifbegin
None.gif print dbo.fgetscript('onlytiancai','sa','sa','database',@name)
None.gif fetch next from #aa into @name
None.gifend
None.gifclose #aa
None.gifdeallocate #aa
None.gif

4、 声明,此函数是csdn邹建邹老大提供的
三、 分隔字符串
如果有一个用逗号分割开的字符串,比如说"a,b,c,d,1,2,3,4",如何用t-sql获取这个字符串有几个元素,获取第几个元素的值是多少呢?因为t-sql里没有split函数,也没有数组的概念,所以只能自己写几个函数了。
1、 获取元素个数的函数

None.gifcreate function getstrarrlength (@str varchar(8000))
None.gifreturns int
None.gifas
None.gifbegin
None.gif declare @int_return int
None.gif declare @start int
None.gif declare @next int
None.gif declare @location int
None.gif select @str =','+ @str +','
None.gif select @str=replace(@str,',,',',')
None.gif select @start =1
None.gif select @next =1
None.gif select @location = charindex(',',@str,@start)
None.gif while (@location <>0)
None.gif begin
None.gif select @start = @location +1
None.gif select @location = charindex(',',@str,@start)
None.gif select @next =@next +1
None.gif end
None.gif select @int_return = @next-2
None.gif return @int_return
None.gifend
None.gif

2、 获取指定索引的值的函数

None.gifcreate function getstrofindex (@str varchar(8000),@index int =0)
None.gifreturns varchar(8000)
None.gifas
None.gifbegin
None.gif declare @str_return varchar(8000)
None.gif declare @start int
None.gif declare @next int
None.gif declare @location int
None.gif select @start =1
None.gif select @next =1 --如果习惯从0开始则select @next =0
None.gif select @location = charindex(',',@str,@start)
None.gif while (@location <>0 and @index > @next )
None.gif begin
None.gif select @start = @location +1
None.gif select @location = charindex(',',@str,@start)
None.gif select @next =@next +1
None.gif end
None.gif if @location =0 select @location =len(@str)+1 --如果是因为没有逗号退出,则认为逗号在字符串后
None.gif select @str_return = substring(@str,@start,@location -@start) --@start肯定是逗号之后的位置或者就是初始值1
None.gif if (@index <> @next ) select @str_return = '' --如果二者不相等,则是因为逗号太少,或者@index小于@next的初始值1。
None.gif return @str_return
None.gifend
None.gif

3、 测试

None.gifSELECT [dbo].[getstrarrlength]('1,2,3,4,a,b,c,d')
None.gifSELECT [dbo].[getstrofindex]('1,2,3,4,a,b,c,d',5)
None.gif

四、 一条语句执行跨越若干个数据库
我要在一条语句里操作不同的服务器上的不同的数据库里的不同的表,怎么办呢?
第一种方法:

None.gifselect * from OPENDATASOURCE('SQLOLEDB','Data Source=远程ip;User ID=sa;Password=密码').库名.dbo.表名
None.gif

第二种方法:
先使用联结服务器:

None.gifEXEC sp_addlinkedserver '别名','','MSDASQL',NULL,NULL,'DRIVER={SQL Server};SERVER=远程名;UID=用户;PWD=密码;'
None.gifexec sp_addlinkedsrvlogin @rmtsrvname='别名',@useself='false',@locallogin='sa',@rmtuser='sa',@rmtpassword='密码'
None.gifGO
None.gif

然后你就可以如下:

None.gifselect * from 别名.库名.dbo.表名
None.gifinsert 库名.dbo.表名 select * from 别名.库名.dbo.表名
None.gifselect * into 库名.dbo.新表名 from 别名.库名.dbo.表名
None.gifgo
None.gif

五、 怎样获取一个表中所有的字段信息
蛙蛙推荐:怎样获取一个表中所有字段的信息
先创建一个视图

None.gifCreate view fielddesc
None.gifas
None.gifselect o.name as table_name,c.name as field_name,t.name as type,c.length as
None.gif
None.giflength,c.isnullable as isnullable,convert(varchar(30),p.value) as desp
None.giffrom syscolumns c
None.gifjoin systypes t on c.xtype = t.xusertype
None.gifjoin sysobjects o on o.id=c.id
None.gifleft join sysproperties p on p.smallid=c.colid and p.id=o.id
None.gifwhere o.xtype='U'
None.gif
None.gif

查询时:

None.gifSelect * from fielddesc where table_name = '你的表名'

还有个更强的语句,是邹建写的,也写出来吧

None.gifSELECT
None.gif (case when a.colorder=1 then d.name else '' end) N'表名',
None.gif a.colorder N'字段序号',
None.gif a.name N'字段名',
None.gif (case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' end) N'标识',
None.gif (case when (SELECT count(*)
None.gif FROM sysobjects
None.gif WHERE (name in
None.gif (SELECT name
None.gif FROM sysindexes
None.gif WHERE (id = a.id) AND (indid in
None.gif (SELECT indid
None.gif FROM sysindexkeys
None.gif WHERE (id = a.id) AND (colid in
None.gif (SELECT colid
None.gif FROM syscolumns
None.gif WHERE (id = a.id) AND (name = a.name))))))) AND
None.gif (xtype = 'PK'))>0 then '√' else '' end) N'主键',
None.gif b.name N'类型',
None.gif a.length N'占用字节数',
None.gif COLUMNPROPERTY(a.id,a.name,'PRECISION') as N'长度',
None.gif isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) as N'小数位数',
None.gif (case when a.isnullable=1 then '√'else '' end) N'允许空',
None.gif isnull(e.text,'') N'默认值',
None.gif isnull(g.[value],'') AS N'字段说明'
None.gif--into ##tx
None.gif
None.gifFROM syscolumns a left join systypes b
None.gifon a.xtype=b.xusertype
None.gifinner join sysobjects d
None.gifon a.id=d.id and d.xtype='U' and d.name<>'dtproperties'
None.gifleft join syscomments e
None.gifon a.cdefault=e.id
None.gifleft join sysproperties g
None.gifon a.id=g.id AND a.colid = g.smallid
None.giforder by object_name(a.id),a.colorder
None.gif
None.gif

六、 时间格式转换问题
因为新开发的软件需要用一些旧软件生成的一些数据,在时间格式上不统一,只能手工转换,研究了一下午写了三条语句,以前没怎么用过convert函数和case语句,还有"+"操作符在不同上下文环境也会起到不同的作用,把我搞晕了要,不过现在看来是差不多弄好了。

1、把所有"70.07.06"这样的值变成"1970-07-06"

None.gifUPDATE lvshi
None.gifSET shengri = '19' + REPLACE(shengri, '.', '-')
None.gifWHERE (zhiyezheng = '139770070153')

2、在"1970-07-06"里提取"70","07","06"

None.gifSELECT SUBSTRING(shengri, 3, 2) AS year, SUBSTRING(shengri, 6, 2) AS month,
None.gif SUBSTRING(shengri, 9, 2) AS day
None.gifFROM lvshi
None.gifWHERE (zhiyezheng = '139770070153')
None.gif

3、把一个时间类型字段转换成"1970-07-06"

None.gifUPDATE lvshi
None.gifSET shenling = CONVERT(varchar(4), YEAR(shenling))
None.gif + '-' + CASE WHEN LEN(MONTH(shenling)) = 1 THEN '0' + CONVERT(varchar(2),
None.gif month(shenling)) ELSE CONVERT(varchar(2), month(shenling))
None.gif END + '-' + CASE WHEN LEN(day(shenling)) = 1 THEN '0' + CONVERT(char(2),
None.gif day(shenling)) ELSE CONVERT(varchar(2), day(shenling)) END
None.gifWHERE (zhiyezheng = '139770070153')
None.gif

七、 分区视图
分区视图是提高查询性能的一个很好的办法

None.gif--看下面的示例
None.gif
None.gif--示例表
None.gifcreate table tempdb.dbo.t_10(
None.gifid int primary key check(id between 1 and 10),name varchar(10))
None.gif
None.gifcreate table pubs.dbo.t_20(
None.gifid int primary key check(id between 11 and 20),name varchar(10))
None.gif
None.gifcreate table northwind.dbo.t_30(
None.gifid int primary key check(id between 21 and 30),name varchar(10))
None.gifgo
None.gif
None.gif--分区视图
None.gifcreate view v_t
None.gifas
None.gifselect * from tempdb.dbo.t_10
None.gifunion all
None.gifselect * from pubs.dbo.t_20
None.gifunion all
None.gifselect * from northwind.dbo.t_30
None.gifgo
None.gif
None.gif--插入数据
None.gifinsert v_t select 1 ,'aa'
None.gifunion all select 2 ,'bb'
None.gifunion all select 11,'cc'
None.gifunion all select 12,'dd'
None.gifunion all select 21,'ee'
None.gifunion all select 22,'ff'
None.gif
None.gif--更新数据
None.gifupdate v_t set name=name+'_更新' where right(id,1)=1
None.gif
None.gif--删除测试
None.gifdelete from v_t where right(id,1)=2
None.gif
None.gif--显示结果
None.gifselect * from v_t
None.gifgo
None.gif
None.gif--删除测试
None.gifdrop table northwind.dbo.t_30,pubs.dbo.t_20,tempdb.dbo.t_10
None.gifdrop view v_t
None.gif
ExpandedBlockStart.gif ContractedBlock.gif/**//*--测试结果
InBlock.gif
InBlock.gifid name
InBlock.gif----------- ----------
InBlock.gif1 aa_更新
InBlock.gif11 cc_更新
InBlock.gif21 ee_更新
InBlock.gif
InBlock.gif(所影响的行数为 3 行)
ExpandedBlockEnd.gif==*/
None.gif None.gif


八、 树型的实现
None.gif

None.gif--参考
None.gif
None.gif--树形数据查询示例
None.gif--作者: 邹建
None.gif
None.gif--示例数据
None.gifcreate table [tb]([id] int identity(1,1),[pid] int,name varchar(20))
None.gifinsert [tb] select 0,'中国'
None.gifunion all select 0,'美国'
None.gifunion all select 0,'加拿大'
None.gifunion all select 1,'北京'
None.gifunion all select 1,'上海'
None.gifunion all select 1,'江苏'
None.gifunion all select 6,'苏州'
None.gifunion all select 7,'常熟'
None.gifunion all select 6,'南京'
None.gifunion all select 6,'无锡'
None.gifunion all select 2,'纽约'
None.gifunion all select 2,'旧金山'
None.gifgo
None.gif
None.gif--查询指定id的所有子
None.gifcreate function f_cid(
None.gif@id int
None.gif)returns @re table([id] int,[level] int)
None.gifas
None.gifbegin
None.gif declare @l int
None.gif set @l=0
None.gif insert @re select @id,@l
None.gif while @@rowcount>0
None.gif begin
None.gif set @l=@l+1
None.gif insert @re select a.[id],@l
None.gif from [tb] a,@re b
None.gif where a.[pid]=b.[id] and b.[level]=@l-1
None.gif end
ExpandedBlockStart.gif ContractedBlock.gif/**//**//**//*--如果只显示最明细的子(下面没有子),则加上这个删除
InBlock.gif delete a from @re a
InBlock.gif where exists(
InBlock.gif select 1 from [tb] where [pid]=a.[id])
ExpandedBlockEnd.gif--*/
None.gif return
None.gifend
None.gifgo
None.gif
None.gif--调用(查询所有的子)
None.gifselect a.*,层次=b.[level] from [tb] a,f_cid(2)b where a.[id]=b.[id]
None.gifgo
None.gif
None.gif--删除测试
None.gifdrop table [tb]
None.gifdrop function f_cid
None.gifgo
None.gif
None.gif

九、 排序问题

None.gifCREATE TABLE [t] (
None.gif [id] [int] IDENTITY (1, 1) NOT NULL ,
None.gif [GUID] [uniqueidentifier] NULL
None.gif) ON [PRIMARY]
None.gifGO


下面这句执行5次

None.gifinsert t values (newid())


查看执行结果

None.gifselect * from t


1、 第一种

None.gifselect * from t
None.gif order by case id when 4 then 1
None.gif when 5 then 2
None.gif when 1 then 3
None.gif when 2 then 4
None.gif when 3 then 5 end


2、 第二种

None.gifselect * from t order by (id+2)%6


3、 第三种

None.gifselect * from t order by charindex(cast(id as varchar),'45123')


4、 第四种

None.gifselect * from t
None.gifWHERE id between 0 and 5
None.giforder by charindex(cast(id as varchar),'45123')


5、 第五种

None.gifselect * from t order by case when id >3 then id-5 else id end


6、 第六种

None.gifselect * from t order by id / 4 desc,id asc

十、 一条语句删除一批记录
首先id列是int标识类类型,然后删除ID值为5,6,8,9,10,11的列,这里的cast函数不能用 convert函数代替,而且转换的类型必须是varchar,而不能是char,否则就会执行出你不希望的结果,这里的"5,6,8,9,10,11" 可以是你在页面上获取的一个chkboxlist构建成的值,然后用下面的一句就全部删
除了,比循环用多条语句高效吧应该。

None.gifdelete from [fujian] where charindex(','+cast([id] as varchar)+',',','+'5,6,8,9,10,11,'+',')>0


还有一种就是

None.gifdelete from table1 where id in(1,2,3,4 dot.gif)


十一、获取子表内的一列数据的组合字符串
下面这个函数获取05年已经注册了的某个所的律师,唯一一个参数就是事务所的名称,然后返回zhuce字段里包含05字样的所有律师。

None.gifCREATE FUNCTION fn_Get05LvshiNameBySuo (@p_suo Nvarchar(50))
None.gifRETURNS Nvarchar(2000)
None.gifAS
None.gifBEGIN
None.gif DECLARE @LvshiNames varchar(2000), @name varchar(50)
None.gif select @LvshiNames=''
None.gif DECLARE lvshi_cursor CURSOR FOR

数据库里有1,2,3,4,5 共5条记录,要用一条sql语句让其排序,使它排列成4,5,1,2,3,怎么写?
None.gif    -- 数据操作
None.gif
None.gif   SELECT -- 从数据库表中检索数据行和列
None.gif        INSERT -- 向数据库表添加新数据行
None.gif        DELETE -- 从数据库表中删除数据行
None.gif        UPDATE -- 更新数据库表中的数据
None.gif
None.gif   -- 数据定义
None.gif
None.gif   CREATE TABLE -- 创建一个数据库表
None.gif        DROP TABLE -- 从数据库中删除表
None.gif        ALTER TABLE -- 修改数据库表结构
None.gif        CREATE VIEW -- 创建一个视图
None.gif        DROP VIEW -- 从数据库中删除视图
None.gif        CREATE INDEX -- 为数据库表创建一个索引
None.gif        DROP INDEX -- 从数据库中删除索引
None.gif        CREATE PROCEDURE -- 创建一个存储过程
None.gif        DROP PROCEDURE -- 从数据库中删除存储过程
None.gif        CREATE TRIGGER -- 创建一个触发器
None.gif        DROP TRIGGER -- 从数据库中删除触发器
None.gif        CREATE SCHEMA -- 向数据库添加一个新模式
None.gif        DROP SCHEMA -- 从数据库中删除一个模式
None.gif        CREATE DOMAIN -- 创建一个数据值域
None.gif        ALTER DOMAIN -- 改变域定义
None.gif        DROP DOMAIN -- 从数据库中删除一个域
None.gif
None.gif   -- 数据控制
None.gif
None.gif   GRANT --

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/93029/viewspace-1023499/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/93029/viewspace-1023499/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值