首页 > 代码库 > 精妙T-SQL语句收集

精妙T-SQL语句收集

SQL语句收集

 1、查看SQL Server版本

SELECT SERVERPROPERTY(‘productversion‘)

SELECT SERVERPROPERTY(‘productlevel‘)

SELECT SERVERPROPERTY(‘edition‘)

SELECT @@VERSION

2、查询Proc或是View内容

proc:

select name,textfrom sys.proceduresa,sys.syscommentsb

wherea.object_id=b.idandtextlike‘%AIS%‘

view:

select name,textfrom sys.viewsa,sys.syscommentsb

wherea.object_id=b.idandtextlike‘%AIS%‘

3、修改SQL定序:

ALTER  DATABASE   xx  COLLATE  Chinese_PRC_CI_AS

4SQL连接OracleDB Link 语法

SELECT * from openquery(链接服务器名称,T-SQL语句)

SELECT * from openquery(xx,‘select* from AISEDI.PBCATCOL‘)

5、在本機創建帳號

 --在本機創建帳號123456

CREATELOGIN[123456] WITHPASSWORD=N‘a123456‘,DEFAULT_DATABASE=[aa],CHECK_POLICY = OFF

GO

--在數據庫上創建帳號123456如果是bak文件或者是附加數據庫就不需要這一句了

USEaa

GO

CREATEUSER[123456] FORLOGIN[123456]

GO

--修復孤立帳號

USE aa

execute sp_change_users_login ‘update_one‘,‘123456‘,‘123456‘

--賦予dbo權限

USE[aa]

GO

EXEC sp_addrolemember N‘db_owner‘,N‘123456‘

6、产生流水码

select replace(str(‘1234‘,流水码位数),char(32),0)

select replace(str(‘1234‘,6),char(32),0) 结果:001234

7、賦予物件public權限

GRANT EXECUTEON[dbo].[proc_w_organization_authInsert]TO[public]

GRANT SELECTON[dbo].[proc_w_organization_authInsert]TO[public]

8、修改SQLServer語言定序

USE aa

go

ALTER DATABASE aa COLLATEChinese_PRC_CI_AS

GO

 

  1. 数据库的完整备份,如下所示:

BACKUP DATABASE DBDEMO

TO DISK=‘D:\Backups\DBDEMO.bak‘

WITH FORMAT

GO

BACKUP LOG DBDEMO

TO DISK=‘D:\Backups\DBDEMO.trn‘

GO

2.用备份档还原数据库

USE master;

go

RESTORE DATABASE DBDEMO

FROM DISK=‘D:\Backups\DBDEMO.bak‘

WITH NORECOVERY

GO

RESTORE LOG DBDEMO

FROM DISK=‘D:\Backups\DBDEMO.trn

WITH NORECOVERY

GO

<2>、如果路徑不同

RESTORE DATABASE DBDEMO

FROM DISK=‘D:\Backups\DBDEMO.bak‘

WITH NORECOVERY,

MOVE‘DBDEMO_Data‘TO

‘D:\MSSQL\Data\DBDEMO_Data.mdf‘,

MOVE‘DBDEMO_Log‘TO

‘D:\MSSQL\Data\DBDEMO_Log.ldf‘;

GO

 

关于取当前日期的年份为查询条件的语句?

能否取服务器当前日期的年份为查询条件?如今天日期为2006-09-13,则查询条件为:

date>=‘2006-01-01‘and date<=‘2006-12-31‘

        解决方法:datediff(year,[date],getdate())=0

or

year([date])=year(getdate())

 2查询所有用户表所有字段详细信息

SELECT

(CASEWHENa.colorder=1THEN d.nameELSE‘‘END) N表名,

a.colorderN字段序号,

a.nameN字段名,

(CASEWHENCOLUMNPROPERTY(a.id,a.name,‘IsIdentity‘)=1THEN‘√‘ELSE‘‘END)N标识,

(CASEWHEN(SELECTCOUNT(*)

FROMsysobjects

WHERE(name in

(SELECTname

FROMsysindexes

WHERE(id = a.id)AND (indidin

(SELECTindid

FROMsysindexkeys

WHERE(id = a.id)AND (colidin

(SELECTcolid

FROMsyscolumns

WHERE(id = a.id)AND (name =a.name))))))) AND

(xtype=‘PK‘))>0THEN‘√‘ELSE‘‘END) N主键,

b.nameN类型,

a.lengthN占用字节数,

COLUMNPROPERTY(a.id,a.name,‘PRECISION‘)AS N长度,

ISNULL(COLUMNPROPERTY(a.id,a.name,‘Scale‘),0)AS N小数位数,

(CASEWHENa.isnullable=1THEN‘√‘ELSE‘‘END)N允许空,

ISNULL(e.text,‘‘)N默认值,

ISNULL(g.[value],‘‘)AS N字段说明


FROMsyscolumns a

LEFTJOINsystypes b ona.xtype=b.xusertype

INNERJOINsysobjects d ona.id=d.idANDd.xtype=‘U‘ANDd.name<>‘dtproperties‘

LEFTJOINsyscomments e ona.cdefault=e.id

LEFTJOINsys.extended_propertiesg ona.id=g.major_idANDa.colid=g.minor_id

WHERE

d.name=表名--要查询的表

ORDERBY

object_name(a.id),a.colorder


3SQLSERVER 2000中各表外键名,主键名的获取


SELECT

外键表ID =b.fkeyid ,

外键表名称=object_name(b.fkeyid),

外键列ID = b.fkey,

外键列名 =(SELECTname FROMsyscolumns WHEREcolid =b.fkey ANDid =b.fkeyid) ,

主键表ID =b.rkeyid ,

主键表名 =object_name(b.rkeyid),

主键列ID = b.rkey,

主键列名 =(SELECTname FROMsyscolumns WHEREcolid =b.rkey ANDid =b.rkeyid) ,

级联更新 =ObjectProperty(a.id,‘CnstIsUpdateCascade‘),

级联删除 =ObjectProperty(a.id,‘CnstIsDeleteCascade‘)

FROMsysobjects a

joinsysforeignkeys b ona.id =b.constid

joinsysobjects c ona.parent_obj =c.id

wherea.xtype =‘f‘ANDc.xtype =‘U‘


精妙SQL语句收集[转载]

精妙SQL语句收集

SQL
语句先前写的时候,很容易把一些特殊的用法忘记,我特此整理了一下SQL语句操作,方便自己写SQL时方便一点,想贴上来,一起看看,同时希望大家能共同多多提意见,也给我留一些更好的佳句,整理一份《精妙SQL速查手册》,不吝赐教!


一、基础

1
、说明:创建数据库
CreateDATABASE database-name
2
、说明:删除数据库
dropdatabase dbname
3
、说明:备份sqlserver
---
创建 备份数据的device
USEmaster
EXEC sp_addumpdevice ‘disk‘, ‘testBack‘,‘c:\mssql7backup\MyNwind_1.dat‘
---
开始备份
BACKUPDATABASE pubs TO testBack
4
、说明:创建新表
createtable tabname(col1 type1 [not null] [primary key],col2 type2 [notnull],..)
根据已有的表创建新表:
A
createtable tab_new like tab_old (使用旧表创建新表)
B
createtable tab_new as select col1,col2… from tab_old definitiononly
5
、说明:删除新表
droptable tabname
6
、说明:增加一个列
Altertable tabname add column coltype
注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。
7
、说明:添加主键:Altertable tabname add primary key(col)
说明:删除主键:Altertable tabname drop primary key(col)
8
、说明:创建索引:create[unique] index idxname on tabname(col….)
删除索引:dropindex idxname
注:索引是不可更改的,想更改必须删除重新建。
9
、说明:创建视图:createview viewname as select statement
删除视图:dropview viewname
10
、说明:几个简单的基本的sql语句
选择:select* from table1 where 范围
插入:insertinto table1(field1,field2) values(value1,value2)
删除:deletefrom table1 where 范围
更新:updatetable1 set field1=value1 where 范围
查找:select* from table1 where field1 like ’%value1%’---like的语法很精妙,查资料!
排序:select* from table1 order by field1,field2 [desc]
总数:selectcount as totalcount from table1
求和:selectsum(field1) as sumvalue from table1
平均:selectavg(field1) as avgvalue from table1
最大:selectmax(field1) as maxvalue from table1
最小:selectmin(field1) as minvalue from table1
11
、说明:几个高级查询运算词
A
UNION运算符
UNION
运算符通过组合其他两个结果表(例如TABLE1TABLE2)并消去表中任何重复行而派生出一个结果表。当ALLUNION一起使用时(即 UNIONALL),不消除重复行。两种情况下,派生表的每一行不是来自TABLE1就是来自 TABLE2
B
EXCEPT运算符
EXCEPT
运算符通过包括所有在TABLE1中但不在 TABLE2中的行并消除所有重复行而派生出一个结果表。当ALLEXCEPT一起使用时 (EXCEPTALL),不消除重复行。
C
INTERSECT运算符
INTERSECT
运算符通过只包括TABLE1TABLE2中都有的行并消除所有重复行而派生出一个结果表。当ALLINTERSECT一起使用时 (INTERSECTALL),不消除重复行。
注:使用运算词的几个查询结果行必须是一致的。
12
、说明:使用外连接
A
leftouter join
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。
SQL:select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a =b.c
B
rightouter join:
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。
C
fullouter join
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。

二、提升

1
、说明:复制表(只复制结构,源表名:a新表名:b)(Access可用)
法一:select* into b from a where 1<>1
法二:selecttop 0 * into b from a

2
、说明:拷贝表(拷贝数据,源表名:a目标表名:b)(Access可用)
insertinto b(a, b, c) select d,e,f from b;

3
、说明:跨数据库之间表的拷贝(具体数据使用绝对路径)(Access可用)
insertinto b(a, b, c) select d,e,f from b in ‘
具体数据库’where条件
例子:..fromb in ‘"&Server.MapPath(".")&"\data.mdb"&"‘ where..

4
、说明:子查询(表名1a表名2b)
selecta,b,c from a where a IN (select d from b )
或者:select a,b,c from a where a IN (1,2,3)

5
、说明:显示文章、提交人和最后回复时间
selecta.title,a.username,b.adddate from table a,(select max(adddate)adddate from table where table.title=a.title) b

6
、说明:外连接查询(表名1a表名2b)
selecta.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a =b.c

7
、说明:在线视图查询(表名1a)
select * from (Select a,b,c FROM a) T where t.a >1;

8
、说明:between的用法,between限制查询数据范围时包括了边界值,notbetween不包括
select* from table1 where time between time1 and time2
select a,b,c,from table1 where a not between
数值1and 数值2

9
、说明:in的使用方法
select* from table1 where a [not] in(‘
1’,’2’,’4’,’6’)

10
、说明:两张关联表,删除主表中已经在副表中没有的信息
deletefrom table1 where not exists ( select * from table2 wheretable1.field1=table2.field1 )

11
、说明:四表联查问题:
select* from a left inner join b on a.a=b.b right inner join c on a.a=c.cinner join d on a.a=d.d where .....

12
、说明:日程安排提前五分钟提醒
SQL:select * from
日程安排wheredatediff(‘minute‘,f开始时间,getdate())>5

13
、说明:一条sql语句搞定数据库分页
selecttop 10 b.* from (select top 20
主键字段,排序字段from表名 orderby 排序字段 desc)a,表名 bwhere b.主键字段 =a.主键字段 orderby a.排序字段

14
、说明:前10条记录
selecttop 10 * form table1 where
范围

15
、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.)
selecta,b,c from tablename ta where a=(select max(a) from tablename tbwhere tb.b=ta.b)

16
、说明:包括所有在TableA中但不在 TableBTableC中的行并消除所有重复行而派生出一个结果表
(selecta from tableA ) except (select a from tableB) except (select a fromtableC)

17
、说明:随机取出10条数据
selecttop 10 * from tablename order by newid()

18
、说明:随机选择记录
selectnewid()

19
、说明:删除重复记录
Deletefrom tablename where id not in (select max(id) from tablename groupby col1,col2,...)

20
、说明:列出数据库里所有的表名
selectname from sysobjects where type=‘U‘

21
、说明:列出表TableNam里的所有的列
selectname from syscolumns whereid=object_id(‘TableName‘)

22
、说明:列示typevenderpcs字段,以type字段排列,case可以方便地实现多重选择,类似select中的case
selecttype,sum(case vender when ‘A‘ then pcs else 0 end),sum(case venderwhen ‘C‘ then pcs else 0 end),sum(case vender when ‘B‘ then pcs else0 end) FROM tablename group by type
显示结果:
typevender pcs
电脑 A1
电脑 A1
光盘 B2
光盘 A2
手机 B3
手机 C3

23
、说明:初始化表table1

TRUNCATETABLE table1

24
、说明:选择从1015的记录
selecttop 5 * from (select top 15 * from table order by id asc) table_
别名orderby id desc

25、查看SQLServer版本

SELECTSERVERPROPERTY(‘productversion‘)

SELECTSERVERPROPERTY(‘productlevel‘)

SELECTSERVERPROPERTY(‘edition‘)

SELECT@@VERSION

26、查询Proc或是View内容

proc:

selectname,textfrom sys.proceduresa,sys.syscommentsb

wherea.object_id=b.idandtextlike‘%AIS%‘


view:

selectname,textfrom sys.viewsa,sys.syscommentsb

wherea.object_id=b.idandtextlike‘%AIS%‘




三、技巧

1
1=11=2的使用,在SQL语句组合时用的较多

“where1=1”
是表示选择全部“where1=2”全部不选,
如:
if@strWhere !=‘‘
begin
set @strSQL = ‘select count(*) as Totalfrom [‘ + @tblName + ‘] where ‘ + @strWhere
end
else
beginelect count(*) as Total from [‘ + @tblName + ‘]‘
end
set @strSQL = ‘s

我们可以直接写成
set@strSQL = ‘select count(*) as Total from [‘ + @tblName + ‘] where 1=1
安定 ‘+@strWhere

2
、收缩数据库
--
重建索引
DBCCREINDEX
DBCC INDEXDEFRAG
--
收缩数据和日志
DBCCSHRINKDB
DBCC SHRINKFILE

3
、压缩数据库
dbccshrinkdatabase(dbname)

4
、转移数据库给新用户以已存在用户权限
execsp_change_users_login‘update_one‘,‘newname‘,‘oldname‘
go

5
、检查备份集
RESTOREVERIFYONLY from disk=‘E:\dvbbs.bak‘

6
、修复数据库
AlterDATABASE [dvbbs] SET SINGLE_USER
GO
DBCCCHECKDB(‘dvbbs‘,repair_allow_data_loss) WITH TABLOCK
GO
AlterDATABASE [dvbbs] SET MULTI_USER
GO

7
、日志清除
SETNOCOUNT ON
DECLARE @LogicalFileName sysname,
@MaxMinutesINT,
@NewSize INT


USE tablename --
要操作的数据库名
Select@LogicalFileName = ‘tablename_log‘, --
日志文件名
@MaxMinutes= 10, -- Limit on time allowed to wrap log.
@NewSize= 1 --
你想设定的日志文件的大小(M)

--Setup / initialize
DECLARE @OriginalSize int
Select@OriginalSize = size
FROM sysfiles
Where name =@LogicalFileName
Select ‘Original Size of ‘ + db_name() + ‘ LOG is‘ +
CONVERT(VARCHAR(30),@OriginalSize) + ‘ 8K pages or ‘ +
CONVERT(VARCHAR(30),(@OriginalSize*8/1024)) + ‘MB‘
FROMsysfiles
Where name = @LogicalFileName
Create TABLEDummyTrans
(DummyColumn char (8000) not null)


DECLARE@Counter INT,
@StartTime DATETIME,
@TruncLogVARCHAR(255)
Select @StartTime = GETDATE(),
@TruncLog = ‘BACKUPLOG ‘ + db_name() + ‘ WITH TRUNCATE_ONLY‘

DBCC SHRINKFILE(@LogicalFileName, @NewSize)
EXEC (@TruncLog)
-- Wrap the logif necessary.
WHILE @MaxMinutes > DATEDIFF (mi, @StartTime,GETDATE()) -- time has not expired
AND @OriginalSize = (Selectsize FROM sysfiles Where name = @LogicalFileName)
AND(@OriginalSize * 8 /1024) > @NewSize
BEGIN -- Outerloop.
Select@Counter = 0
WHILE ((@Counter < @OriginalSize / 16) AND(@Counter < 50000))
BEGIN -- update
Insert DummyTrans VALUES(‘Fill Log‘)
Delete DummyTrans
Select @Counter = @Counter +1
END
EXEC (@TruncLog)
END
Select ‘Final Size of ‘ +db_name() + ‘ LOG is ‘ +
CONVERT(VARCHAR(30),size) + ‘ 8K pages or‘ +
CONVERT(VARCHAR(30),(size*8/1024)) + ‘MB‘
FROM sysfiles
Where name = @LogicalFileName
Drop TABLE DummyTrans
SETNOCOUNT OFF

8
、说明:更改某个表
execsp_changeobjectowner ‘tablename‘,‘dbo‘

9
、存储更改全部表

CreatePROCEDURE dbo.User_ChangeObjectOwnerBatch
@OldOwner asNVARCHAR(128),
@NewOwner as NVARCHAR(128)
AS

DECLARE@Name as NVARCHAR(128)
DECLARE @Owner as NVARCHAR(128)
DECLARE@OwnerName as NVARCHAR(128)

DECLARE curObject CURSOR FOR
select ‘Name‘ = name,
‘Owner‘ = user_name(uid)
fromsysobjects
where user_name(uid)=@OldOwner
order by name

OPENcurObject
FETCH NEXT FROM curObject INTO @Name,@Owner
WHILE(@@FETCH_STATUS=0)
BEGIN
if @Owner=@OldOwner
begin
set @OwnerName = @OldOwner + ‘.‘ + rtrim(@Name)
execsp_changeobjectowner @OwnerName, @NewOwner
end
-- select@name,@NewOwner,@OldOwner

FETCH NEXT FROM curObject INTO@Name, @Owner
END

close curObject
deallocatecurObject
GO


10
SQLSERVER中直接循环写入数据
declare@i int
set @i=1
while @i<30
begin
insert into test(userid) values(@i)
set @i=@i+1
end