sql语句集锦

--取m到n条记录
select identity(int) ido ,* into #temp1order from table3
select * from #temp1order where ido>2 and ido<5
exec sp_dboption northwind,'select into/bulkcopy',true --执行第一条语句时报错,打开属性
select * from #temp1order where identitycol between 2 and 5
--数据备份
use master
exec sp_addumpdevice 'disk','testback','d:/testbak'
backup database msdb to testback
backup database msdb to disk='d:/test1.bak'
--根据原表创建新表
create table newproducts2 like table products
create table newproducts1 as select productID, productname from products definition only
select * into newproducts from products where 1<>1
--添加主键
alter table newproducts add primary key(productID)
--添加列
alter table newproducts add column (testid,varchar)
--创建、删除索引
create unique index productsid on newproducts(productID)
drop index newproducts.productsid
--统计行数
select count(*) as tablecount from products
--跨库查询
select * into itemss01class from zw0008..fitemss01class
select * into fitemss01 from zw0008..fitemss01 where 1<>1
--跨实列名查询或跨服务器查询
select * into fitemss01 from openrowset ('SQLOLEDB','taojf';'sa';'1','SELECT * FROM zw0008..fitemss01 where 1<>1')
insert into fitemss01 select  substring (xmdm,3,7)as citemcode,xmmc as citemname, 0 as bclose ,substring(xmdm,3,5)as citemccode, null as iotherused, xmdm as U8_R9
from gl_xmzl where xmdm>'01' and gsdm='2008'

select * from table1
select * from table2
select top 0* into newproducts1 from products
insert into newproducts select * from products
..from b in '"&Server.MapPath("taojf")&"/data.mdb" &"' where..
insert into anyigl select * from anyigl in '"&Server.MapPath("taojf")&"/anyisys.mdb" &"'
select * from anyigl
--having用法
select productid,sum(unitprice)  as total from orderdetails  group by productid having sum(unitprice)>100   order by productid
select productid ,count(*) from orderdetails  group by productid
select productid,sum(unitprice)  as total from orderdetails  group by productid having count (*)>20 order by productid
select productid,sum(quantity) as total  from orderdetails group by productid having count(*)<10 order by productid
select * from orderdetails  having avg(unitprice)>5
--创建外键约束
alter table neworders1 add constraint pk_neworders1_id primary key (orderid)
alter table neworders2 add constraint pk_neworders2_id primary key (orderid)
select orderid from (select * from neworders1 union select *  from neworders2 )
a group by orderid having count(*)>1
--查询数据的最大排序问题
CREATE TABLE hard (qu char (11) ,co char (11) ,je numeric(3, 0))
insert into hard values ('A','1',3)
insert into hard values ('A','2',4)
insert into hard values ('A','4',2)
insert into hard values ('A','6',9)
insert into hard values ('B','1',4)
insert into hard values ('B','2',5)
insert into hard values ('B','3',6)
insert into hard values ('C','3',4)
insert into hard values ('C','6',7)
insert into hard values ('C','2',3)
insert into hard values ('D','2',3)
insert into hard values ('E','2',3)
insert into hard values ('D','2',3)
select * from hard a where je in (select top 2 je from hard b where b.qu=a.qu order by b.je desc)order by qu,a.je desc
--得到当前日期
select getdate()
--分页
select top 10 b.* from (select top 20 orderid,productid from orderdetails order by orderid desc)
a,orderdetails b where b.orderid=a.orderid order by a.orderid
--随机取数
select top 10 * from orders order by newid()
select newid()
DECLARE @myid uniqueidentifier
SET @myid = NEWID()
PRINT 'Value of @myid is: '+ CONVERT(varchar(255), @myid)
select name from sysobjects where type='U'
select name from syscolumns where id=object_id('orderdetails')
--truncate初始化表用法
select count(*) beforetr from newproducts
truncate table newproducts
select count(*) aftertr from newproducts
select * from newproducts
--取表的5到8行的数据
select top 8* from orderdetails order by orderid asc,productid asc
select * from  (select top 5 * from (select top 8  * from orderdetails order by  orderid asc,productid asc)a order by orderid desc, productid desc)b order by orderid asc,productid asc
--删除重复行
create table a_dist(id int,name varchar(20))

insert into a_dist values(1,'abc')
insert into a_dist values(1,'abc')
insert into a_dist values(1,'abc')
insert into a_dist values(1,'abc')

exec up_distinct 'a_dist','id'
select * from a_dist

alter procedure up_distinct(@t_name varchar(30),@f_key varchar(30))
--f_key表示是分组字段﹐即主键字段
as
begin
declare @max integer,@id varchar(30) ,@sql varchar(7999) ,@type integer
select @sql = 'declare cur_rows cursor for select '+@f_key+' ,count(*) from ' +@t_name +' group by ' +@f_key +' having count(*) > 1'
exec(@sql)
open cur_rows
fetch cur_rows into @id,@max
while @@fetch_status=0
begin
select @max = @max -1
set rowcount @max
select @type = xtype from syscolumns where id=object_id(@t_name) and name=@f_key
if @type=56
select @sql = 'delete from '+@t_name+' where ' + @f_key+' = '+ @id
if @type=167
select @sql = 'delete from '+@t_name+' where ' + @f_key+' = '+''''+ @id +''''
exec(@sql)
fetch cur_rows into @id,@max
end
close cur_rows
deallocate cur_rows
set rowcount 0
end

--select * from systypes
--select * from syscolumns where id = object_id('a_dist')
--行列转换合并
create table a_test(name varchar(20),role2 varchar(20))
insert into a_test values('李','管理员')
insert into a_test values('张','管理员')
insert into a_test values('张','一般用户')
insert into a_test values('常','一般用户')

create function join_str(@content varchar(100))
returns varchar(2000)
as
begin
declare @str varchar(2000)
set @str=''
select @str=@str+','+rtrim(role2) from a_test where [name]=@content
select @str=right(@str,len(@str)-1)
return @str
end
go
select [name],dbo.join_str([name]) role2 from a_test group by [name]
select * from a_test
--select distinct name,dbo.uf_test(name) from a_test

创建一个合并的函数
create function fmerg(@id int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str=''
select @str=@str+','+cast(pid as varchar) from 表A where id=@id
set @str=right(@str,len(@str)-1)
return(@str)
End
go
 
select distinct id,dbo.fmerg(id) from 表A
--行列转换--普通

declare @sql varchar(4000)
set @sql = 'select Name'
select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result end) ['+Subject+']'
from (select distinct Subject from CJ) as a
select @sql = @sql+' from test group by name'
exec(@sql)

--最近回复查询
select a.productname,a.unitprice,b.discount from products a,(select max(unitprice) unitprice from products where products.unitprice=a.unitprice)b
--列出表里的所有的列
select name from syscolumns where id=object_id('TableName')
--方法如下:先从SYSTEMOBJECT系统表中取得数据表的SYSTEMID,然后再SYSCOLUMN表中取得该数据表的所有列名。
SQL语句如下:
declare @objid int,@objname char(40)
set @objname = 'tablename'
select @objid = id from sysobjects where id = object_id(@objname)
select 'Column_name' = name from syscolumns where id = @objid order by colid
--或
SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='users'
--列出数据库里所有的表名
select name from sysobjects where type='U'
--通过SQL语句来更改用户的密码
修改别人的,需要sysadmin role
EXEC sp_password NULL, 'newpassword', 'User'
--怎么判断出一个表的哪些字段不允许为空?
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where IS_NULLABLE='NO' and TABLE_NAME='tablename'
--a. 查已知列名的情况
SELECT b.name as TableName,a.name as columnname
From syscolumns a INNER JOIN sysobjects b
ON a.id=b.id
AND b.type='U'
AND a.name='你的字段名字'
--未知列名查所有在不同表出现过的列名
Select o.name As tablename,s1.name As columnname
From syscolumns s1, sysobjects o
Where s1.id = o.id
And o.type = 'U'
And Exists (
Select 1 From syscolumns s2
Where s1.name = s2.name
And s1.id <> s2.id
)
--取某XXX行数据
select * from (select top xxx * from yourtable order by id asc) aa
where not exists(select 1 from (select top xxx-1 * from yourtable order id asc) bb
where aa.id=bb.id)
select * from  (select  top 34 * from orders order by orderid ) a where orderid not in (select orderid from (select top 33  * from orders order by orderid)b)
select * from (select  top 34 * from orders order by orderid)a where orderid not in (select orderid from (select top 33  * from orders order by orderid)b)
--下面测试不可行,取不到数据
select * from (select  top 34 * from orders order by orderid asc)a where not exists (select top 33 * from orders order by orderid asc)
--exists =any 用法
select distinct s.orderid from orders s where s.orderid=any(select od.orderid from  orderdetails od)
select distinct s.orderid from orders s where exists (select od.orderid from  orderdetails od where s.orderid=od.orderid)
--如果使用游标也是可以的
fetch absolute [number] from [cursor_name]
--快速获取表test的记录总数
select rows from sysindexes where id=object_id('orders') and indid in (0,1)
select count (*)  as rows from orders
--从左边截取
select left(len('orders')-1,1)

backup database CDMS to disk='d:/CDMS/c.bak ' --备份
restore database CDMS from disk='d:/CDMS/bbb.bak '--恢复

--数据库附加
EXEC sp_attach_db @dbname = N'pubs',
@filename1 = N'c:/Program Files/Microsoft SQL Server/MSSQL/Data/pubs.mdf',
@filename2 = N'c:/Program Files/Microsoft SQL Server/MSSQL/Data/pubs_log.ldf'

EXEC sp_attach_db @dbname = N'Ty20051029101451aaa',
@filename1 = N'd:/5屏幕/Ty20051029101451aaa_data.mdf',
@filename2 = N'd:/5屏幕/Ty20051029101451aaa_log.ldf'


--分离数据库
可以使用 sp_detach_db 存储过程分离该数据库,然后使用带有 FOR ATTACH 子句的 CREATE DATABASE 重新附加。
sp_detach_db Archive
GO
CREATE DATABASE Archive
ON PRIMARY (FILENAME = 'c:/program files/microsoft sqlserver/mssql/data/archdat1.mdf')
FOR ATTACH
GO


//脱机语句
alter   database   [数据库名]   set   offline
//联机语句
alter   database   [数据库名]   set   online

alter   database   [数据库名]   set   offline with   rollback   after   10
//清除连接

--同库跨表更新 aaa

update aaa set aaa.a=bbb.a from aaa,bbb where aaa.b=bbb.b

--跨库更新zw0002..cccc

update zw0002..cccc set zw0002..cccc.a=bbb.a from bbb,zw0002..cccc where zw0002..cccc.b=bbb.b
--日期算當月天數
select Day(dateadd(day,-1,convert(datetime,convert(char(07),dateadd(m,1,getdate()),120)+'-01')))
   select 32-Day(getdate()+(32-Day(getdate()))) days
--按姓氏笔画排序
select * from gl_pznr order by zy Collate Chinese_PRC_Stroke_ci_as desc
--按拼音首字母排序
select * from 表名 order by 列名 Collate Chinese_PRC_CS_AS_KS_WS
--查看硬盘分区:
EXEC master..xp_fixeddrives
--得到表中最小的未使用的ID号
SELECT (CASE WHEN
   EXISTS(SELECT * FROM orders b WHERE b.orderid = 1)
    THEN MIN(orderid) + 1 ELSE 1 END) AS orderid
  FROM orders WHERE NOT orderid IN (SELECT a.orderid - 1 FROM orders a)
--删除重复行
delete from neworderdetails
where orderid not in
(
select max(orderid) from neworderdetails group by productid
)

create table tablename(
序号 int ,
姓名 varchar(80),
日期 varchar(50)
)

go

insert tablename select 1,'张三','20051102'
union select 2,'张三','20051104'
union select 3,'张三','20051105'
union select 4,'张三','20051107'
union select 5,'李四','20051102'
union select 6,'李四','20051111'
union select 7,'王五','20051116'
union select 8,'王五','20051109'
union select 9,'张三','20051122'

go
---查询
select * from tablename
 where 序号 in(
   select 序号 from tablename a
      where not exists(
         select * from tablename b
            where b.序号=a.序号-1 and b.姓名=a.姓名
        ))

set nocount on
--75151448行数据
select count(*) from syscolumns a,syscolumns b,syscolumns c
set statistics time on

 select top 10 * from(
select a.name as name,left(b.name,10) as name1, checksum(newid()) as hash
    from syscolumns a,syscolumns b,syscolumns c )t
 where hash%100=0


set statistics time off
set nocount off
declare @t int
set @T = 1000   --计算40的阶乘
SET NOCOUNT  ON
declare @ta table(id int identity(1,1),col bigint)
insert @ta(col) select 1

declare @n int,@i int,@c bigint,@len int,@tmp bigint,@tp bigint

set @len=1;
set @n = @t
while (@n >=1)
begin
    select @c = 0 ,@i = 1
    select @tmp = col from @ta where id = @i
    while (@i <= @len)
    begin
        set @tmp = @tmp*@n+@c
        set @tp = @tmp
        set @tmp = @tmp % 10000;
       
        update @ta
        set col = @tmp where id = @i;
        set @c = @tp / 10000
        set @i = @i + 1
        if not exists(select 1 from @ta where id = @i)
             insert @ta (col) select 0
        select @tmp = col from @ta where id = @i
    end
    update @ta
       set col = @c where id = @i;
    if (@c>0)
        set @len = @len +  1
    set @n = @n - 1
end

declare @s varchar(8000)
 
select @s = isnull(@s+' ','')+right('0000'+ltrim(col),4)
from  @ta
order by id desc
select @s

SET NOCOUNT  Off

你可能感兴趣的:(sql,数据库,table,database,insert,statistics)