T-SQL

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

 

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.gif
go
None.gif
None.gif
create 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.gif
as
None.gif
begin
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.gif
end
None.gif
go
None.gif
None.gif

2、 用法如下
用法如下,

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

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

None.gifdeclare @name varchar(250)
None.gif
declare #aa cursor for
None.gif 
select name from sysobjects where xtype not in('S','PK','D','X','L')
None.gif
open #aa
None.gif
fetch next from #aa into @name
None.gif
while @@fetch_status=0
None.gif
begin
None.gif 
print dbo.fgetscript('onlytiancai','sa','sa','database',@name)
None.gif 
fetch next from #aa into @name
None.gif
end
None.gif
close #aa
None.gif
deallocate #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.gif
returns int
None.gif
as
None.gif
begin
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.gif
end
None.gif

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

None.gifcreate function getstrofindex (@str varchar(8000),@index int =0)
None.gif
returns varchar(8000)
None.gif
as
None.gif
begin
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.gif
end
None.gif

3、 测试

None.gifSELECT [dbo].[getstrarrlength]('1,2,3,4,a,b,c,d')
None.gif
SELECT [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.gif
exec sp_addlinkedsrvlogin  @rmtsrvname='别名',@useself='false',@locallogin='sa',@rmtuser='sa',@rmtpassword='密码'
None.gif
GO
None.gif

然后你就可以如下:

None.gifselect * from 别名.库名.dbo.表名
None.gif
insert 库名.dbo.表名 select * from 别名.库名.dbo.表名
None.gif
select * into 库名.dbo.新表名 from 别名.库名.dbo.表名
None.gif
go
None.gif

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

None.gifCreate view fielddesc    
None.gif
as
None.gif
select 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.gif
from syscolumns c  
None.gif
join systypes t on c.xtype = t.xusertype
None.gif
join sysobjects o on o.id=c.id 
None.gif
left join    sysproperties p on p.smallid=c.colid and p.id=o.id    
None.gif
where 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'),0as 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.gif
FROM  syscolumns  a left join systypes b 
None.gif
on  a.xtype=b.xusertype
None.gif
inner join sysobjects d 
None.gif
on a.id=d.id  and  d.xtype='U' and  d.name<>'dtproperties'
None.gif
left join syscomments e
None.gif
on a.cdefault=e.id
None.gif
left join sysproperties g
None.gif
on a.id=g.id AND a.colid = g.smallid  
None.gif
order by object_name(a.id),a.colorder
None.gif
None.gif

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

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

None.gifUPDATE lvshi
None.gif
SET shengri = '19' + REPLACE(shengri, '.''-')
None.gif
WHERE (zhiyezheng = '139770070153')

 

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

None.gifSELECT SUBSTRING(shengri, 32AS yearSUBSTRING(shengri, 62AS month
None.gif      
SUBSTRING(shengri, 92AS day
None.gif
FROM lvshi
None.gif
WHERE (zhiyezheng = '139770070153')
None.gif

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

None.gifUPDATE lvshi
None.gif
SET 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.gif
WHERE (zhiyezheng = '139770070153')
None.gif

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

None.gif--看下面的示例
None.gif

None.gif
--示例表
None.gif
create table tempdb.dbo.t_10(
None.gifid 
int primary key check(id between 1 and 10),name varchar(10))
None.gif
None.gif
create table pubs.dbo.t_20(
None.gifid 
int primary key check(id between 11 and 20),name varchar(10))
None.gif
None.gif
create table northwind.dbo.t_30(
None.gifid 
int primary key check(id between 21 and 30),name varchar(10))
None.gif
go
None.gif
None.gif
--分区视图
None.gif
create view v_t
None.gif
as
None.gif
select * from tempdb.dbo.t_10
None.gif
union all
None.gif
select * from pubs.dbo.t_20
None.gif
union all
None.gif
select * from northwind.dbo.t_30
None.gif
go
None.gif
None.gif
--插入数据
None.gif
insert v_t select 1 ,'aa'
None.gif
union  all select 2 ,'bb'
None.gif
union  all select 11,'cc'
None.gif
union  all select 12,'dd'
None.gif
union  all select 21,'ee'
None.gif
union  all select 22,'ff'
None.gif
None.gif
--更新数据
None.gif
update v_t set name=name+'_更新' where right(id,1)=1
None.gif
None.gif
--删除测试
None.gif
delete from v_t where right(id,1)=2
None.gif
None.gif
--显示结果
None.gif
select * from v_t
None.gif
go
None.gif
None.gif
--删除测试
None.gif
drop table northwind.dbo.t_30,pubs.dbo.t_20,tempdb.dbo.t_10
None.gif
drop view v_t
None.gif
ExpandedBlockStart.gifContractedBlock.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.gif
create table [tb]([id] int identity(1,1),[pid] int,name varchar(20))
None.gif
insert [tb] select 0,'中国'
None.gif
union  all  select 0,'美国'
None.gif
union  all  select 0,'加拿大'
None.gif
union  all  select 1,'北京'
None.gif
union  all  select 1,'上海'
None.gif
union  all  select 1,'江苏'
None.gif
union  all  select 6,'苏州'
None.gif
union  all  select 7,'常熟'
None.gif
union  all  select 6,'南京'
None.gif
union  all  select 6,'无锡'
None.gif
union  all  select 2,'纽约'
None.gif
union  all  select 2,'旧金山'
None.gif
go
None.gif
None.gif
--查询指定id的所有子
None.gif
create function f_cid(
None.gif
@id int
None.gif)
returns @re table([id] int,[level] int)
None.gif
as
None.gif
begin
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.gifContractedBlock.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.gif
end
None.gif
go
None.gif
None.gif
--调用(查询所有的子)
None.gif
select a.*,层次=b.[level] from [tb] a,f_cid(2)b where a.[id]=b.[id]
None.gif
go
None.gif
None.gif
--删除测试
None.gif
drop table [tb]
None.gif
drop function f_cid
None.gif
go
None.gif
None.gif

 

九、 排序问题


数据库里有1,2,3,4,5 共5条记录,要用一条sql语句让其排序,使它排列成4,5,1,2,3,怎么写?
None.gifCREATE TABLE [t] (
None.gif 
[id] [int] IDENTITY (11NOT NULL ,
None.gif 
[GUID] [uniqueidentifier] NULL 
None.gif
ON [PRIMARY]
None.gif
GO


下面这句执行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.gif
WHERE id between 0 and 5
None.gif
order 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.gif
RETURNS Nvarchar(2000)
None.gif
AS
None.gif
BEGIN  
None.gif 
DECLARE @LvshiNames varchar(2000), @name varchar(50)
None.gif 
select @LvshiNames=''
None.gif 
DECLARE lvshi_cursor CURSOR FOR
None.gif 
select [name] from [lvshi] where charindex(','+'05'+',',','+zhuce+',')>0 and suo=@p_suo order by id desc
None.gif 
OPEN lvshi_cursor
None.gif 
FETCH NEXT FROM lvshi_cursor
None.gif 
INTO @name
None.gif 
WHILE @@FETCH_STATUS = 0
None.gif 
BEGIN
None.gif     
SELECT @LvshiNames = @LvshiNames + @name + ','
None.gif  
fETCH NEXT FROM lvshi_cursor 
None.gif  
INTO @name
None.gif 
END
None.gif 
CLOSE lvshi_cursor
None.gif 
DEALLOCATE lvshi_cursor
None.gif 
RETURN(@LvshiNames)
None.gif
END
None.gif

十二、让0变成1,1变成0

None.gifdeclare @a int
None.gif
set @a =0 --初始为0
None.gif
select @a
None.gif
set @a = @a^1 --把0变成1
None.gif
select @a
None.gif
set @a = @a^1 --把1变成0
None.gif
select @a

转载于:https://www.cnblogs.com/VirtualMJ/archive/2007/01/22/627091.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值