标签:
http://topic.csdn.net/u/20080920/15/424c77bf-7610-4888-be85-9a43e70f55c6.html?4728 http://topic.csdn.net/u/20090310/17/0b8f60c5-9304-4633-84fa-d176f282cb7d.html (1) 固定列数的行列转换 (2) --SQL2005
CREATE TABLE #t (id int IDENTITY(1,1) PRIMARY KEY,nums int) GO
INSERT INTO #t SELECT abs(CHECKSUM(NEWID())%100000) GO 10000 ----生成10000笔资料,可以是任意一数字
SELECT * FROM #t GO DROP TABLE #t GO (3) --日期转换参数,值得收藏 select CONVERT(varchar, getdate(), 120 ) 2004-09-12 11:06:08
select replace(replace(replace(CONVERT(varchar, getdate(), 120 ),‘-‘,‘‘),‘ ‘,‘‘),‘:‘,‘‘) 20040912110608
select CONVERT(varchar(12) , getdate(), 111 ) 2004/09/12
select CONVERT(varchar(12) , getdate(), 112 ) 20040912
select CONVERT(varchar(12) , getdate(), 102 ) 2004.09.12
其它我不常用的日期格式转换方法:
select CONVERT(varchar(12) , getdate(), 101 ) 09/12/2004
select CONVERT(varchar(12) , getdate(), 103 ) 12/09/2004
select CONVERT(varchar(12) , getdate(), 104 ) 12.09.2004
select CONVERT(varchar(12) , getdate(), 105 ) 12-09-2004
select CONVERT(varchar(12) , getdate(), 106 ) 12 09 2004
select CONVERT(varchar(12) , getdate(), 107 ) 09 12, 2004
select CONVERT(varchar(12) , getdate(), 108 ) 11:06:08
select CONVERT(varchar(12) , getdate(), 109 ) 09 12 2004 1
select CONVERT(varchar(12) , getdate(), 110 ) 09-12-2004
select CONVERT(varchar(12) , getdate(), 113 ) 12 09 2004 1
select CONVERT(varchar(12) , getdate(), 114 ) 11:06:08.177 (4) /* 标题:普通行列转换(version 2.0) 作者:爱新觉罗.毓华(十八年风雨,守得冰山雪莲花开) 时间:2008-03-09 地点:广东深圳 说明:普通行列转换(version 1.0)仅针对sql server 2000提供静态和动态写法,version 2.0增加sql server 2005的有关写法。
问题:假设有张学生成绩表(tb)如下: 姓名 课程 分数 张三 语文 74 张三 数学 83 张三 物理 93 李四 语文 74 李四 数学 84 李四 物理 94 想变成(得到如下结果): 姓名 语文 数学 物理 ---- ---- ---- ---- 李四 74 84 94 张三 74 83 93 ------------------- */
create table tb(姓名 varchar(10) , 课程 varchar(10) , 分数 int) insert into tb values(‘张三‘ , ‘语文‘ , 74) insert into tb values(‘张三‘ , ‘数学‘ , 83) insert into tb values(‘张三‘ , ‘物理‘ , 93) insert into tb values(‘李四‘ , ‘语文‘ , 74) insert into tb values(‘李四‘ , ‘数学‘ , 84) insert into tb values(‘李四‘ , ‘物理‘ , 94) go
--SQL SERVER 2000 静态SQL,指课程只有语文、数学、物理这三门课程。(以下同) select 姓名 as 姓名 , max(case 课程 when ‘语文‘ then 分数 else 0 end) 语文, max(case 课程 when ‘数学‘ then 分数 else 0 end) 数学, max(case 课程 when ‘物理‘ then 分数 else 0 end) 物理 from tb group by 姓名
--SQL SERVER 2000 动态SQL,指课程不止语文、数学、物理这三门课程。(以下同) declare @sql varchar(8000) set @sql = ‘select 姓名 ‘ select @sql = @sql + ‘ , max(case 课程 when ‘‘‘ + 课程 + ‘‘‘ then 分数 else 0 end) [‘ + 课程 + ‘]‘ from (select distinct 课程 from tb) as a set @sql = @sql + ‘ from tb group by 姓名‘ exec(@sql)
--SQL SERVER 2005 静态SQL。 select * from (select * from tb) a pivot (max(分数) for 课程 in (语文,数学,物理)) b
--SQL SERVER 2005 动态SQL。 declare @sql varchar(8000) select @sql = isnull(@sql + ‘],[‘ , ‘‘) + 课程 from tb group by 课程 set @sql = ‘[‘ + @sql + ‘]‘ exec (‘select * from (select * from tb) a pivot (max(分数) for 课程 in (‘ + @sql + ‘)) b‘)
---------------------------------
/* 问题:在上述结果的基础上加平均分,总分,得到如下结果: 姓名 语文 数学 物理 平均分 总分 ---- ---- ---- ---- ------ ---- 李四 74 84 94 84.00 252 张三 74 83 93 83.33 250 */
--SQL SERVER 2000 静态SQL。 select 姓名 姓名, max(case 课程 when ‘语文‘ then 分数 else 0 end) 语文, max(case 课程 when ‘数学‘ then 分数 else 0 end) 数学, max(case 课程 when ‘物理‘ then 分数 else 0 end) 物理, cast(avg(分数*1.0) as decimal(18,2)) 平均分, sum(分数) 总分 from tb group by 姓名
--SQL SERVER 2000 动态SQL。 declare @sql varchar(8000) set @sql = ‘select 姓名 ‘ select @sql = @sql + ‘ , max(case 课程 when ‘‘‘ + 课程 + ‘‘‘ then 分数 else 0 end) [‘ + 课程 + ‘]‘ from (select distinct 课程 from tb) as a set @sql = @sql + ‘ , cast(avg(分数*1.0) as decimal(18,2)) 平均分 , sum(分数) 总分 from tb group by 姓名‘ exec(@sql)
--SQL SERVER 2005 静态SQL。 select m.* , n.平均分 , n.总分 from (select * from (select * from tb) a pivot (max(分数) for 课程 in (语文,数学,物理)) b) m, (select 姓名 , cast(avg(分数*1.0) as decimal(18,2)) 平均分 , sum(分数) 总分 from tb group by 姓名) n where m.姓名 = n.姓名
--SQL SERVER 2005 动态SQL。 declare @sql varchar(8000) select @sql = isnull(@sql + ‘,‘ , ‘‘) + 课程 from tb group by 课程 exec (‘select m.* , n.平均分 , n.总分 from (select * from (select * from tb) a pivot (max(分数) for 课程 in (‘ + @sql + ‘)) b) m , (select 姓名 , cast(avg(分数*1.0) as decimal(18,2)) 平均分 , sum(分数) 总分 from tb group by 姓名) n where m.姓名 = n.姓名‘)
drop table tb
------------------ ------------------
/* 问题:如果上述两表互相换一下:即表结构和数据为: 姓名 语文 数学 物理 张三 748393 李四 748494 想变成(得到如下结果): 姓名 课程 分数 ---- ---- ---- 李四 语文 74 李四 数学 84 李四 物理 94 张三 语文 74 张三 数学 83 张三 物理 93 -------------- */
create table tb(姓名 varchar(10) , 语文 int , 数学 int , 物理 int) insert into tb values(‘张三‘,74,83,93) insert into tb values(‘李四‘,74,84,94) go
--SQL SERVER 2000 静态SQL。 select * from ( select 姓名 , 课程 = ‘语文‘ , 分数 = 语文 from tb union all select 姓名 , 课程 = ‘数学‘ , 分数 = 数学 from tb union all select 姓名 , 课程 = ‘物理‘ , 分数 = 物理 from tb ) t order by 姓名 , case 课程 when ‘语文‘ then 1 when ‘数学‘ then 2 when ‘物理‘ then 3 end
--SQL SERVER 2000 动态SQL。 --调用系统表动态生态。 declare @sql varchar(8000) select @sql = isnull(@sql + ‘ union all ‘ , ‘‘ ) + ‘ select 姓名 , [课程] = ‘ + quotename(Name , ‘‘‘‘)+ ‘ , [分数] = ‘ + quotename(Name) + ‘ from tb‘ from syscolumns where name! = N‘姓名‘ and ID = object_id(‘tb‘) --表名tb,不包含列名为姓名的其它列 order by colid asc exec(@sql + ‘ order by 姓名 ‘)
--SQL SERVER 2005 动态SQL。 select 姓名 , 课程 , 分数 from tb unpivot (分数 for 课程 in([语文] , [数学] , [物理])) t
--SQL SERVER 2005 动态SQL,同SQL SERVER 2000 动态SQL。
-------------------- /* 问题:在上述的结果上加个平均分,总分,得到如下结果: 姓名 课程 分数 ---- ------ ------ 李四 语文 74.00 李四 数学 84.00 李四 物理 94.00 李四 平均分 84.00 李四 总分 252.00 张三 语文 74.00 张三 数学 83.00 张三 物理 93.00 张三 平均分 83.33 张三 总分 250.00 ------------------ */
select * from ( select 姓名 as 姓名 , 课程 = ‘语文‘ , 分数 = 语文 from tb union all select 姓名 as 姓名 , 课程 = ‘数学‘ , 分数 = 数学 from tb union all select 姓名 as 姓名 , 课程 = ‘物理‘ , 分数 = 物理 from tb union all select 姓名 as 姓名 , 课程 = ‘平均分‘ , 分数 = cast((语文 + 数学 + 物理)*1.0/3 as decimal(18,2)) from tb union all select 姓名 as 姓名 , 课程 = ‘总分‘ , 分数 = 语文 + 数学 + 物理 from tb ) t order by 姓名 , case 课程 when ‘语文‘ then 1 when ‘数学‘ then 2 when ‘物理‘ then 3 when ‘平均分‘ then 4 when ‘总分‘ then 5 end
drop table tb (5) --按某一字段分组取最大(小)值所在行的数据 --(爱新觉罗.毓华(十八年风雨,守得冰山雪莲花开) 2007-10-23于浙江杭州) /* 数据如下: name val memo a 2 a2(a的第二个值) a 1 a1--a的第一个值 a 3 a3:a的第三个值 b 1 b1--b的第一个值 b 3 b3:b的第三个值 b 2 b2b2b2b2 b 4 b4b4 b 5 b5b5b5b5b5 */ --创建表并插入数据: create table tb(name varchar(10),val int,memo varchar(20)) insert into tb values(‘a‘, 2, ‘a2(a的第二个值)‘) insert into tb values(‘a‘, 1, ‘a1--a的第一个值‘) insert into tb values(‘a‘, 3, ‘a3:a的第三个值‘) insert into tb values(‘b‘, 1, ‘b1--b的第一个值‘) insert into tb values(‘b‘, 3, ‘b3:b的第三个值‘) insert into tb values(‘b‘, 2, ‘b2b2b2b2‘) insert into tb values(‘b‘, 4, ‘b4b4‘) insert into tb values(‘b‘, 5, ‘b5b5b5b5b5‘) go
--一、按name分组取val最大的值所在行的数据。 --方法1: select a.* from tb a where val = (select max(val) from tb where name = a.name) order by a.name --方法2: select a.* from tb a where not exists(select 1 from tb where name = a.name and val > a.val) --方法3: select a.* from tb a,(select name,max(val) val from tb group by name) b where a.name = b.name and a.val = b.val order by a.name --方法4: select a.* from tb a inner join (select name , max(val) val from tb group by name) b on a.name = b.name and a.val = b.val order by a.name --方法5 select a.* from tb a where 1 > (select count(*) from tb where name = a.name and val > a.val ) order bya.name /* name val memo ---------- ----------- -------------------- a 3 a3:a的第三个值 b 5 b5b5b5b5b5 */
--二、按name分组取val最小的值所在行的数据。 --方法1: select a.* from tb a where val = (select min(val) from tb where name = a.name) order by a.name --方法2: select a.* from tb a where not exists(select 1 from tb where name = a.name and val < a.val) --方法3: select a.* from tb a,(select name,min(val) val from tb group by name) b where a.name = b.name and a.val = b.val order by a.name --方法4: select a.* from tb a inner join (select name , min(val) val from tb group by name) b on a.name = b.name and a.val = b.val order by a.name --方法5 select a.* from tb a where 1 > (select count(*) from tb where name = a.name and val < a.val) order bya.name /* name val memo ---------- ----------- -------------------- a 1 a1--a的第一个值 b 1 b1--b的第一个值 */
--三、按name分组取第一次出现的行所在的数据。 select a.* from tb a where val = (select top 1 val from tb where name = a.name) order by a.name /* name val memo ---------- ----------- -------------------- a 2 a2(a的第二个值) b 1 b1--b的第一个值 */
--四、按name分组随机取一条数据。 select a.* from tb a where val = (select top 1 val from tb where name = a.name order by newid()) orderby a.name /* name val memo ---------- ----------- -------------------- a 1 a1--a的第一个值 b 5 b5b5b5b5b5 */
--五、按name分组取最小的两个(N个)val select a.* from tb a where 2 > (select count(*) from tb where name = a.name and val < a.val ) order bya.name,a.val select a.* from tb a where val in (select top 2 val from tb where name=a.name order by val) order bya.name,a.val select a.* from tb a where exists (select count(*) from tb where name = a.name and val < a.val havingCount(*) < 2) order by a.name /* name val memo ---------- ----------- -------------------- a 1 a1--a的第一个值 a 2 a2(a的第二个值) b 1 b1--b的第一个值 b 2 b2b2b2b2 */
--六、按name分组取最大的两个(N个)val select a.* from tb a where 2 > (select count(*) from tb where name = a.name and val > a.val ) order bya.name,a.val select a.* from tb a where val in (select top 2 val from tb where name=a.name order by val desc) orderby a.name,a.val select a.* from tb a where exists (select count(*) from tb where name = a.name and val > a.val havingCount(*) < 2) order by a.name /* name val memo ---------- ----------- -------------------- a 2 a2(a的第二个值) a 3 a3:a的第三个值 b 4 b4b4 b 5 b5b5b5b5b5 */ --七,如果整行数据有重复,所有的列都相同。 /* 数据如下: name val memo a 2 a2(a的第二个值) a 1 a1--a的第一个值 a 1 a1--a的第一个值 a 3 a3:a的第三个值 a 3 a3:a的第三个值 b 1 b1--b的第一个值 b 3 b3:b的第三个值 b 2 b2b2b2b2 b 4 b4b4 b 5 b5b5b5b5b5 */ --在sql server 2000中只能用一个临时表来解决,生成一个自增列,先对val取最大或最小,然后再通过自增列来取数据。 --创建表并插入数据: create table tb(name varchar(10),val int,memo varchar(20)) insert into tb values(‘a‘, 2, ‘a2(a的第二个值)‘) insert into tb values(‘a‘, 1, ‘a1--a的第一个值‘) insert into tb values(‘a‘, 1, ‘a1--a的第一个值‘) insert into tb values(‘a‘, 3, ‘a3:a的第三个值‘) insert into tb values(‘a‘, 3, ‘a3:a的第三个值‘) insert into tb values(‘b‘, 1, ‘b1--b的第一个值‘) insert into tb values(‘b‘, 3, ‘b3:b的第三个值‘) insert into tb values(‘b‘, 2, ‘b2b2b2b2‘) insert into tb values(‘b‘, 4, ‘b4b4‘) insert into tb values(‘b‘, 5, ‘b5b5b5b5b5‘) go
select * , px = identity(int,1,1) into tmp from tb
select m.name,m.val,m.memo from ( select t.* from tmp t where val = (select min(val) from tmp where name = t.name) ) m where px = (select min(px) from ( select t.* from tmp t where val = (select min(val) from tmp where name = t.name) ) n where n.name = m.name)
drop table tb,tmp
/* name val memo ---------- ----------- -------------------- a 1 a1--a的第一个值 b 1 b1--b的第一个值
(2 行受影响) */ --在sql server 2005中可以使用row_number函数,不需要使用临时表。 --创建表并插入数据: create table tb(name varchar(10),val int,memo varchar(20)) insert into tb values(‘a‘, 2, ‘a2(a的第二个值)‘) insert into tb values(‘a‘, 1, ‘a1--a的第一个值‘) insert into tb values(‘a‘, 1, ‘a1--a的第一个值‘) insert into tb values(‘a‘, 3, ‘a3:a的第三个值‘) insert into tb values(‘a‘, 3, ‘a3:a的第三个值‘) insert into tb values(‘b‘, 1, ‘b1--b的第一个值‘) insert into tb values(‘b‘, 3, ‘b3:b的第三个值‘) insert into tb values(‘b‘, 2, ‘b2b2b2b2‘) insert into tb values(‘b‘, 4, ‘b4b4‘) insert into tb values(‘b‘, 5, ‘b5b5b5b5b5‘) go
select m.name,m.val,m.memo from ( select * , px = row_number() over(order by name , val) from tb ) m where px = (select min(px) from ( select * , px = row_number() over(order by name , val) from tb ) n where n.name = m.name)
drop table tb
/* name val memo ---------- ----------- -------------------- a 1 a1--a的第一个值 b 1 b1--b的第一个值
(2 行受影响) */ (6) 合并列值 (7) 分拆列值 (8) /*
标题:分解字符串并查询相关数据
作者:爱新觉罗.毓华(十八年风雨,守得冰山雪莲花开) 时间:2008-03-18 地点:广东深圳
说明:通过使用函数等方法分解字符串查询相关数据。
问题:通过分解一个带某种符号分隔的字符串在数据库中查找相关数据。
例如 @str = ‘1,2,3‘,查询下表得到记录1,4,5,6 ID TypeID
1 1,2,3,4,5,6,7,8,9,10,11,12
2 2,3
3 3,7,8,9
4 2,6
5 4,5
6 6,7
*/
-----------------------------
create table tb (ID int , TypeID varchar(30)) insert into tb values(1 , ‘1,2,3,4,5,6,7,8,9,10,11,12‘) insert into tb values(2 , ‘2,3‘) insert into tb values(3 , ‘3,7,8,9‘) insert into tb values(4 , ‘2,6‘) insert into tb values(5 , ‘4,5‘) insert into tb values(6 , ‘6,7‘) go
-----------------------------
--如果仅仅是一个,如@str = ‘1‘. declare @str as varchar(30) set @str = ‘1‘ select * from tb where charindex(‘,‘ + @str + ‘,‘ , ‘,‘ + TypeID + ‘,‘) > 0 select * from tb where ‘,‘ + TypeID + ‘,‘ like ‘%,‘ + @str + ‘,%‘ /*
ID TypeID
----------- ------------------------------
1 1,2,3,4,5,6,7,8,9,10,11,12
(所影响的行数为 1 行) */
-----------------------------
--如果包含两个,如@str = ‘1,2‘. declare @str as varchar(30) set @str = ‘1,2‘ select * from tb where charindex(‘,‘ + left(@str , charindex(‘,‘ , @str) - 1) + ‘,‘ , ‘,‘ + typeid + ‘,‘) > 0 or charindex(‘,‘ + substring(@str , charindex(‘,‘ , @str) + 1 , len(@str)) + ‘,‘ , ‘,‘ + typeid + ‘,‘) > 0 select * from tb where ‘,‘ + typeid + ‘,‘ like ‘%,‘ + left(@str , charindex(‘,‘ , @str) - 1) + ‘,%‘ or ‘,‘ + typeid + ‘,‘ like ‘%,‘ + substring(@str , charindex(‘,‘ , @str) + 1 , len(@str)) + ‘,%‘ /*
ID TypeID
----------- ------------------------------
1 1,2,3,4,5,6,7,8,9,10,11,12
2 2,3
4 2,6
(所影响的行数为 3 行) */
-------------------------------------------
--如果包含三个或四个,用PARSENAME函数来处理. declare @str as varchar(30) set @str = ‘1,2,3,4‘ select * from tb where charindex(‘,‘ + parsename(replace(@str , ‘,‘ , ‘.‘) , 4) + ‘,‘ , ‘,‘ + typeid + ‘,‘) > 0 or charindex(‘,‘ + parsename(replace(@str , ‘,‘ , ‘.‘) , 3) + ‘,‘ , ‘,‘ + typeid + ‘,‘) > 0 or charindex(‘,‘ + parsename(replace(@str , ‘,‘ , ‘.‘) , 2) + ‘,‘ , ‘,‘ + typeid + ‘,‘) > 0 or charindex(‘,‘ + parsename(replace(@str , ‘,‘ , ‘.‘) , 1) + ‘,‘ , ‘,‘ + typeid + ‘,‘) > 0 select * from tb where ‘,‘ + typeid + ‘,‘ like ‘%,‘ + parsename(replace(@str , ‘,‘ , ‘.‘) , 4) + ‘,%‘ or ‘,‘ + typeid + ‘,‘ like ‘%,‘ + parsename(replace(@str , ‘,‘ , ‘.‘) , 3) + ‘,%‘ or ‘,‘ + typeid + ‘,‘ like ‘%,‘ + parsename(replace(@str , ‘,‘ , ‘.‘) , 2) + ‘,%‘ or ‘,‘ + typeid + ‘,‘ like ‘%,‘ + parsename(replace(@str , ‘,‘ , ‘.‘) , 1) + ‘,%‘ /*
ID TypeID
----------- ------------------------------
1 1,2,3,4,5,6,7,8,9,10,11,12
2 2,3
3 3,7,8,9
4 2,6
5 4,5
(所影响的行数为 5 行) */
---------------------------------------
--如果超过四个,则只能使用函数或动态SQL来分解并查询数据。 /*
名称:fn_split函数. 功能:实现字符串分隔功能的函数
*/
create function dbo.fn_split(@inputstr varchar(8000), @seprator varchar(10)) returns @temp table (a varchar(200)) as
begin
declare @i int set @inputstr = rtrim(ltrim(@inputstr)) set @i = charindex(@seprator , @inputstr) while @i >= 1 begin
insert @temp values(left(@inputstr , @i - 1)) set @inputstr = substring(@inputstr , @i + 1 , len(@inputstr) - @i) set @i = charindex(@seprator , @inputstr) end
if @inputstr <> ‘\‘ insert @temp values(@inputstr) return
end
go
--调用 declare @str as varchar(30) set @str = ‘1,2,3,4,5‘ select distinct m.* from tb m, (select * from dbo.fn_split(@str,‘,‘)) n where charindex(‘,‘ + n.a + ‘,‘ , ‘,‘ + m.typeid + ‘,‘) > 0 drop table tb drop function dbo.fn_split /*
ID TypeID
----------- ------------------------------
1 1,2,3,4,5,6,7,8,9,10,11,12
2 2,3
3 3,7,8,9
4 2,6
5 4,5
(所影响的行数为 5 行) */
------------------------------------------
--使用动态SQL的语句。 declare @str varchar(200) declare @sql as varchar(1000) set @str = ‘1,2,3,4,5‘ set @sql = ‘select ‘‘‘ + replace(@str , ‘,‘ , ‘‘‘ as id union all select ‘‘‘) set @sql = @sql + ‘‘‘‘ set @sql = ‘select distinct a.* from tb a , (‘ + @sql + ‘) b where charindex(‘ + ‘‘‘,‘‘ + b.id + ‘ + ‘‘‘,‘‘‘ + ‘ , ‘ +‘‘‘,‘‘ + a.typeid + ‘ + ‘‘‘,‘‘‘ + ‘) > 0 ‘ exec (@sql) /*
ID TypeID
----------- ------------------------------
1 1,2,3,4,5,6,7,8,9,10,11,12
2 2,3
3 3,7,8,9
4 2,6
5 4,5
(所影响的行数为 5 行) */
(9) --返程问题,找出雇员从本地出发后直接返回的情况 create table trav(name nvarchar(10),date datetime,comefrom nvarchar(10),destin nvarchar(10),id int) insert into trav select ‘张三‘,‘2007-01-01‘,‘上海‘,‘广州‘,1 insert into trav select ‘李四‘,‘2007-01-01‘,‘上海‘,‘广州‘,2 insert into trav select ‘李四‘,‘2007-02-01‘,‘上海‘,‘成都‘,3 insert into trav select ‘张三‘,‘2007-01-15‘,‘广州‘,‘上海‘,4 insert into trav select ‘张三‘,‘2007-02-06‘,‘上海‘,‘广州‘,5 insert into trav select ‘张三‘,‘2007-02-18‘,‘广州‘,‘上海‘,6 go
select a.name,a.date,a.comefrom,a.destin,b.date,b.comefrom,b.destin
from trav a inner join trav b on a.name=b.name and a.comefrom=b.destin and a.destin=b.comefrom where a.id<b.id and not exists(select 1 from trav where comefrom=b.comefrom and date<b.date and date>a.date) go
drop table trav /*
name date comefrom destin date comefrom destin
---------- ----------------------- ---------- ---------- ----------------------- ---------- ----------
张三 2007-01-01 00:00:00.000 上海 广州 2007-01-15 00:00:00.000 广州 上海 张三 2007-02-06 00:00:00.000 上海 广州 2007-02-18 00:00:00.000 广州 上海
(2 行受影响) */
(10) --库存先进先出简单例子:
create table t( id int identity(1,1), name varchar(50),--商品名称 j int, --入库数量 c int, --出库数量 jdate datetime --入库时间 ) insert into t(name,j,c,jdate) select ‘A‘,100,0,‘2007-12-01‘ insert into t(name,j,c,jdate) select ‘A‘,200,0,‘2008-01-07‘ insert into t(name,j,c,jdate) select ‘B‘,320,0,‘2007-12-21‘ insert into t(name,j,c,jdate) select ‘A‘,100,0,‘2008-01-15‘ insert into t(name,j,c,jdate) select ‘B‘,90,0,‘2008-02-03‘ insert into t(name,j,c,jdate) select ‘A‘,460,0,‘2008-02-01‘ insert into t(name,j,c,jdate) select ‘A‘,510,0,‘2008-03-01‘ go
create proc wsp @name varchar(50),--商品名称 @cost int --销售量 as --先得出该货物的库存是否够 declare @spare float --剩余库存 select @spare=sum(j)-sum(c) from t where name=@name if(@spare>=@cost) begin --根据入库日期采用先进先出原则对货物的库存进行处理 update t set c= case when (select @cost-isnull(sum(j),0)+isnull(sum(c),0) from t where name=@name and jdate<=a.jdate and j!=c)>=0 then a.j else case when (select @cost-isnull(sum(j),0)+isnull(sum(c),0) from t where name=@name and jdate<a.jdate and j!=c)<0 then 0 else (select @cost-isnull(sum(j),0)+isnull(sum(c),0)+a.c from t where name=@name and jdate<a.jdate and j!=c) end end from t a where name=@name and j!=c end else raiserror(‘库存不足‘,16,1) return go
--测试:
exec wsp @name=‘A‘,@cost=180 select * from t
--drop table t --drop proc wsp (11) 1. 查看数据库的版本 (12)--bom结构,查找节点下所有子节点: create table os(id int,parentid int,desn varchar(10)) insert into os select 1,0,‘体育用品‘ insert into os select 2,0,‘户外运动‘ insert into os select 3,1,‘篮球‘ insert into os select 4,1,‘足球‘ insert into os select 5,2,‘帐篷‘ insert into os select 6,2,‘登山鞋‘ insert into os select 7,0,‘男士用品‘ insert into os select 8,7,‘刮胡刀‘ insert into os select 9,3,‘大号篮球‘ --求个节点下所有子节点: create function f_cid(@id int) returns varchar(500) as
begin
declare @t table(id int,parentid int,desn varchar(10),lev int) declare @lev int set @lev=1 insert into @t select *,@lev from os where id=@id while(@@rowcount>0) begin
set @lev=@lev+1 insert into @t select a.*,@lev from os a,@t b where a.parentid=b.id and b.lev=@lev-1 end
declare @cids varchar(500) select @cids=isnull(@cids+‘,‘,‘‘)+ltrim(id) from @t order by lev return @cids end
go
--调用函数 select *,ids=dbo.f_cid(id) from os --得到每个节点路径: create proc wsp2 @id int as
select *,cast(‘ ‘ as varchar(10)) fullpath into #os from os DECLARE @i int,@j int set @i=0 set @j=1 select @i=max(parentid) from #os update #os set fullpath=id while @j<=@i begin
update #os set fullpath=a.fullpath+‘,‘+ltrim(#os.id) from #os inner join #os a on #os.parentid=a.id where #os.parentid=@j set @j=@j+1 end
select * from #os go
--调用存储过程 exec wsp2 1 (13) set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go
ALTER trigger [tri_updatesalary_Mem_Type] on [dbo].[SalaryIncrease] after insert
as
declare @i int set @i=@@identity update m
set m.Mem_Type=case when s.SMark>500000 then ‘退休会员‘--500000 when s.SMark>400000 then ‘钻石五级‘--400000 when s.SMark>300000 then ‘钻石四级‘--300000 when s.SMark>200000 then ‘钻石三级‘--200000 when s.SMark>100000 then ‘钻石二级‘--100000 when s.SMark>50000 then ‘钻石一级‘--50000 when s.SMark>40000 then ‘五星级‘--40000 when s.SMark>30000 then ‘四星级‘--30000 when s.SMark>20000 then ‘三星级‘--20000 when s.SMark>10000 then ‘二星级‘--10000 when s.SMark>5000 then ‘一星级‘--5000 else ‘一般VIP会员‘ end
from MemberInfo m
join (select s.SCardName,sum(s.SMark) as SMark from SalaryIncrease s join inserted i on s.SCardName=i.SCardName group by s.SCardName) s on m.Mem_Num=s.SCardName --if exists(select * from MemberInfo m join inserted i on m.Mem_Num=i.SCardName and m.Mem_Mark>100 )
if exists (select m.SCardName,sum(m.ShopMark)as mark from(select m.SCardName,m.ShopMark from ShoppingMark m join inserted i on m.SCardName=i.SCardName where year(m.SDate)=year(getdate()) and month(m.SDate)=month(getdate())) m group by m.SCardName having sum(m.ShopMark)>100) /**/
/* --最新的(我写的,上面是整合魅影的)select * from ShoppingMark SM join (select m.SCardName,sum(m.ShopMark) as Mark from ShoppingMark m join inserted i on m.SCardName=i.SCardName group by m.SCardName) s on SM.SCardName=s.ScardName where month(SDate)=month(getdate()) and year(SDate)=year(getdate()) and s.Mark>100*/
begin
update s
set s.SIncease=case --积分大于1000就是星级.所以不用判断是否是星级 when m.Mem_Type<>‘一般VIP会员‘ then s.SMark*0.3 else case when s.SMark>4000 then s.SMark*0.3 -- when s.SMark>4000 then
-- 200*0.2+200*0.23+200*0.25+200*0.28+(s.SMark-800)*0.3
when s.SMark>3000 then 1000*0.2+1000*0.23+1000*0.25+(s.SMark-600)*0.28 when s.SMark>2000 then 1000*0.2+100*0.23+(s.SMark-400)*0.25 when s.SMark>1000 then (s.SMark-200)*.023+1000*0.2 else s.SMark*0.2 end
end
from SalaryIncrease as s join inserted i
on s.SCardName=i.SCardName join MemberInfo m
on (i.SCardName=m.Mem_Num and s.SID=@i) or (i.SCardName=m.Mem_Num and s.SIncease=0) end
--go
(14) create table tb(id varchar(3) , pid varchar(3) , name varchar(10)) insert into tb values(‘001‘ , null , ‘广东省‘) insert into tb values(‘002‘ , ‘001‘ , ‘广州市‘) insert into tb values(‘003‘ , ‘001‘ , ‘深圳市‘) insert into tb values(‘004‘ , ‘002‘ , ‘天河区‘) insert into tb values(‘005‘ , ‘003‘ , ‘罗湖区‘) insert into tb values(‘006‘ , ‘003‘ , ‘福田区‘) insert into tb values(‘007‘ , ‘003‘ , ‘宝安区‘) insert into tb values(‘008‘ , ‘007‘ , ‘西乡镇‘) insert into tb values(‘009‘ , ‘007‘ , ‘龙华镇‘) insert into tb values(‘010‘ , ‘007‘ , ‘松岗镇‘) go
--查询指定节点及其所有子节点的函数 create function f_cid(@ID varchar(3)) returns @t_level table(id varchar(3) , level int) as begin declare @level int set @level = 1 insert into @t_level select @id , @level while @@ROWCOUNT > 0 begin set @level = @level + 1 insert into @t_level select a.id , @level from tb a , @t_Level b where a.pid = b.id and b.level = @level - 1 end return end go
--调用函数查询001(广东省)及其所有子节点 select a.* from tb a , f_cid(‘001‘) b where a.id = b.id order by a.id /* id pid name ---- ---- ---------- 001 NULL 广东省 002 001 广州市 003 001 深圳市 004 002 天河区 005 003 罗湖区 006 003 福田区 007 003 宝安区 008 007 西乡镇 009 007 龙华镇 010 007 松岗镇
(所影响的行数为 10 行) */
--调用函数查询002(广州市)及其所有子节点 select a.* from tb a , f_cid(‘002‘) b where a.id = b.id order by a.id /* id pid name ---- ---- ---------- 002 001 广州市 004 002 天河区
(所影响的行数为 2 行) */
--调用函数查询003(深圳市)及其所有子节点 select a.* from tb a , f_cid(‘003‘) b where a.id = b.id order by a.id /* id pid name ---- ---- ---------- 003 001 深圳市 005 003 罗湖区 006 003 福田区 007 003 宝安区 008 007 西乡镇 009 007 龙华镇 010 007 松岗镇
(所影响的行数为 7 行) */
drop table tb drop function f_cid (15) /* 标题:日期分表查询(version 1.0) 网名:悬崖边的舞者 时间:2008-07-14 地点:天津 说明:以日期或月份分表进行多日、多月查询连表查询的有关写法 */
Create Procedure Search @date1 datetime, --起始时间 @date2 datetime --终止时间 as declare @date1New datetime, @rq varchar(6), @i int , --记录循环次数 @s varchar(5000) --根据表多少 可以扩大它 set @rq=convert(varchar,@date1,12) --把时间格式化 比如2008-06-20 变成了080620
set @s=‘select * from sensor‘+@rq --初始化 @s=‘select * from sensor080620‘ 这样第一个表就有了
set @i=datediff(d,@date1,@date2) --日期相减
while @i>0 begin --如果是非常重要的系统可以在这里加上该物理表是否存在的语句 --if exists(select * from dbo.sysobjects where --id = object_id(N‘c‘) and OBJECTPROPERTY(id,N‘IsUserTable‘)=1) --begin --SELECT ‘存在 ‘ --end
set @date1New= dateadd(day,@i,@date1) set @rq=convert(varchar,@date1New,12) --如果是按月进行查询 就修改上面 set @s= @s+‘ union all select * from sensor‘+@rq set @i=@i-1 --累加 end
select @s --exec(@S) go
exec Search ‘2008-06-20 00:11:11.000‘,‘2008-07-25 00:11:11.000‘ drop Procedure Search
(16) 知识点:SQL函数主要分为两中类型 1.单行函数(也叫标量函数) 2.多行函数 /*08.09.20*/
select * from employee
use master /*显示表结构*/ exec sp_helpdb GO
use pubs exec sp_help GO
use pubs exec sp_help employee GO
select lname,job_lvl from employee where job_lvl<=50
select lname,job_lvl/*使用BETWEEN条件*/ from employee where job_lvl BETWEEN 100 AND 200
select lname,job_id,job_lvl/*使用IN成员条件测试在列表中的值*/ from employee where job_lvl IN (100,170,200)
select emp_id,lname,job_id,job_lvl/*使用NOT操作*/ from employee where job_lvl NOT IN(100,170,200)
select title_id,title,type,price from titles where price IS NULL
select lname,job_lvl,job_lvl/*优先规则AND在前*/ from employee where job_lvl=5 OR job_lvl=7 AND job_lvl>160
select lname,job_lvl,job_lvl/*用圆括号强制优先权*/ from employee where (job_lvl=5 OR job_lvl=7) AND job_lvl>160
select lname,job_id,job_lvl,hire_date/*用ORDER BY子句进行排序(升序排列)*/ from employee ORDER BY hire_date
select lname,job_id,job_lvl,hire_date/*用DESC降序排列*/ from employee ORDER BY hire_date DESC
select emp_id,lname,job_lvl*2 "Double job_lvl"/*用列别名排序*/ from employee ORDER BY "Double job_lvl"
select lname,job_id,job_lvl/*多列排序*/ from employee ORDER BY job_id,job_lvl DESC
/* 小结下:主要掌握WHERE子句限制输出行 使用比较条件 使用BETWEEN,IN,AND,NOT,OR操作 最后掌握使用ORDER BY子句排序输出行 所有操作在数据库pubs里进行 */ (17) --改变用户的锁定状态 (可适合一切 bit 类型的字段)
UPDATE tb_Table SET IsLook=Abs(IsLook-1) WHERE Id=@id (18) 1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用) (19) --功能概述:显示某一表的结构
DECLARE @tableName nvarchar(100) SET @tableName =‘brand‘
--mssql2005 SELECT ( CASE WHEN a.colorder=1 THEN d.name ELSE ‘‘ END)表名, a.colorder 字段序号, a.name 字段名, (CASE WHEN COLUMNPROPERTY( a.id,a.name,‘IsIdentity‘)=1 THEN ‘√‘ ELSE ‘‘ END) 标识, (CASE WHEN ( SELECT COUNT(*) FROM sysobjects WHERE (name IN (SELECT name FROM sysindexes WHERE (id = a.id) AND (indid IN (SELECT indid FROM sysindexkeys WHERE (id = a.id) AND (colid IN (SELECT colid FROM syscolumns WHERE (id = a.id) AND (name = a.name))))))) AND (xtype = ‘PK‘))>0 THEN ‘√‘ ELSE ‘‘ END) 主键, b.name 类型, a.length 占用字节数, COLUMNPROPERTY(a.id,a.name,‘PRECISION‘) AS 长度, ISNULL(COLUMNPROPERTY(a.id,a.name,‘Scale‘),0) AS 小数位数, (CASE WHEN a.isnullable=1 THEN ‘√‘ ELSE ‘‘ END) 允许空, ISNULL(e.text,‘‘) 默认值, ISNULL(g.[value],‘‘) AS 字段说明 FROM syscolumns a LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects d ON a.id=d.id AND d.xtype=‘U‘ AND d.name <>‘dtproperties‘ LEFT JOIN syscomments e ON a.cdefault=e.id LEFT JOIN sys.extended_properties g ON a.id=g.major_id AND a.colid = g.major_id WHERE d.name=@tableName ORDER BY a.id,a.colorder (20) --功能概述:重新编译一个表上的所有索引
alter index all on order_master rebuild (21) *--比较两个数据库的表结构差异 求字串中所含某字符或某子串的个数 (23) USE MASTER--连接系统数据库 IF EXISTS(select 1 from master..sysdatabases where name=‘bankDB‘) DROP DATABASE bankDB GO
-----------------------------------------------建库------------------ --打开外围服务器 EXEC sp_configure ‘show advanced options‘, 1 GO
RECONFIGURE
GO
EXEC sp_configure ‘xp_cmdshell‘, 1 GO
RECONFIGURE
GO
--新建文件夹 exec xp_cmdshell ‘MD e:\数据库‘ CREATE DATABASE bankDB ON
( NAME =‘bankDB‘, FILENAME=‘e:\数据库\bankDB.mdf‘, SIZE = 10, MAXSIZE=500, FILEGROWTH=15% ) GO
--------------------------------------------------建表----------------- USE bankDB
--用户信息表 IF EXISTS(select 1 from bankDB..sysobjects where name=‘userInfo‘) DROP TABLE userInfo GO
CREATE TABLE userInfo ( customerID int identity(1,1) PRIMARY KEY , --顾客编号(自动增长 主键) customerName varchar(20) not null, --开户名 PID varchar(20)UNIQUE not null, --身份证(18-15位数 唯一约束) telephone varchar(20) not null, --联系电话(****-********或手机号11位数) [address] ntext --联系地址 ) --银行卡信息表 IF EXISTS(select 1 from bankDB..sysobjects where name=‘cardInfo‘) DROP TABLE cardInfo GO
CREATE TABLE cardInfo ( cardID varchar(20) primary key , --卡号 (格式为1010 3576 **** ***(*部分是随机产生)) curType varchar(10) default(‘RMB‘) not null,--货币种类 (默认为RMB) savingType varchar(10), --存款类型 (活期/定活两便/定期) openDate datetime default(getdate()) not null,--开户日期 (默认为当前时间) openMoney money check(openMoney<1) not null, --开户金额 (不能低于1元) dalance money check(dalance<1) not null, --余额 (不能低于1元 否则将销户) pass varchar(20) default(888888) not null,--密码 (6位数 开户时默认为6个8) IsReportLoss bit default(0) not null, --是否过失 (是/否 默认为否 1是 0否) customerID int not null --顾客编号 (外键 该卡号对应的顾客编号 一个用户可办多张卡) ) --交易信息表 IF EXISTS(select 1 from bankDB..sysobjects where name=‘transInfo‘) DROP TABLE transInfo GO
CREATE TABLE transInfo ( transDate datetime not null, --交易日期(默认为当前时间) cardID varchar(20) not null, --卡号(外键 可重复索引) transType varchar(10) not null, --交易类型(只能是存入/支取) transMoney money check(transMoney>0) not null, --交易金额(大于0) remark ntext --备注(其它说明) ) ------------------------------约束------------------------------- --约束电话和手机号码 if(object_id(‘uq_pid‘) is not null) begin
alter table userinfo drop constraint uq_pid end
if(object_id(‘ck_PID‘) is not null) begin
alter table userinfo drop constraint ck_PID end
if(object_id(‘ck_telephone‘) is not null) begin
alter table userinfo drop constraint ck_telephone end
alter table userInfo add constraint ck_PID check(len(pid) in (15,18)), constraint uq_PID unique(pid), constraint ck_telephone check(telephone like ‘1[35][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]‘--约束手机号码 or
telephone like ‘[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]‘--010-12345678 or
telephone like ‘[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]‘--0719-12345678 or
telephone like ‘[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9]‘)--0719-1234567 ----------------------------------------------设置卡号为随机数(方法1)--------------------------- declare @r decimal(10,8) declare @time varchar(25) set @time=convert(varchar,getdate(),120)+convert(varchar,datepart(ms,getdate())) set @time=replace(@time,‘ ‘,‘‘) set @time=replace(@time,‘:‘,‘‘) set @time=replace(@time,‘-‘,‘‘) set @time=substring(@time,8,len(@time)-1) --select @time--查看获得的随机数 select @r=rand(convert(bigint,@time)) set @time=cast(@r as varchar) --select @time
set @time=substring(@time,3,len(@time)-1) print @time print ‘1001‘+convert(varchar(10),@time) ----------------------------------------------设置卡号为随机数(方法2用了 存储过程)--------------------------- create proc proc_randCardID @cardid varchar(19) output as
declare @r numeric(8,8) set @cardid=‘1010 3657 ‘ while(1=1) begin
set @r=rand(datepart(mm,getdate())*100000+datepart(ss,getdate())*1000+datepart(ms,getdate())) declare @temp char(8) set @temp=substring(convert(varchar,@r),3,8) set @cardid=@cardid+substring(@temp,1,4)+‘ ‘+substring(@temp,5,4) if not exists(select 1 from cardinfo where cardid=@cardid) break
end
--测试(调用存储过程) declare @card varchar(19) exec proc_randCardID @card output print @card */
(24) 我来一段.用友U870中,生产订单欠料查询,我自己写的,优化后的语句我就不贴了 SQL code
SELECT mom.Moid,mom.MoCode,mom.CreateDate,mom.MoDid,mom.Qty, mom.QualifiedInQty, mom.InvCode,mom.momName,mom.momStd,mom.RelsDate,mom.CloseDate, list.allocateId,list.listinvcode,Inventory.cInvName,cInvStd,list.listQty,list.IssQty,list.WhCode,rd.impoids,rd.NonTakeNum,rd.TakeNum,rd.NonReQNum,rd.ReQNum,rd.NonReMNum,rd.ReMNum, CASE WHEN listQty-rd.TakeNum-rd.NonReQNum-rd.ReQNum-rd.NonReMNum-rd.ReMNum<=0 THEN0 ELSE listQty-rd.TakeNum-rd.NonReQNum-rd.ReQNum-rd.NonReMNum-rd.ReMNum END AS CurPlanNum, pl.tinvcode,pl.tqty,pl.tIssqty,pl.tNonTakeNum,pl.tTakeNum,pl.tNonReQNum,pl.tReQNum,pl.tNonReMNum,pl.tReMNum, CASE WHEN pl.tqty-pl.tTakeNum-pl.tNonReQNum-pl.tReQNum-pl.tNonReMNum-pl.tReMNum<=0THEN 0 ELSE pl.tqty-pl.tTakeNum-pl.tNonReQNum-pl.tReQNum-pl.tNonReMNum-pl.tReMNumEND AS TotPlanNum, ISNULL(CurrentStock.iQuantity,0) AS iQuantity, ISNULL(CurrentStock.fInQuantity,0) AS fInQuantity,CurrentStock.cWhCode, CASE WHEN list.listQty-rd.TakeNum-rd.NonReQNum-rd.ReQNum-rd.NonReMNum-rd.ReMNum<=0THEN ISNULL(CurrentStock.iQuantity,0)+ISNULL(CurrentStock.fInQuantity,0) ELSE ISNULL(CurrentStock.iQuantity,0)+ISNULL(CurrentStock.fInQuantity,0)-( list.listQty-rd.TakeNum-rd.NonReQNum-rd.ReQNum-rd.NonReMNum-rd.ReMNum) END AS CurAppNum, CASE WHEN pl.tqty-pl.tTakeNum-pl.tNonReQNum-pl.tReQNum-pl.tNonReMNum-pl.tReMNum<=0THEN ISNULL(CurrentStock.iQuantity,0)+ISNULL(CurrentStock.fInQuantity,0) ELSE ISNULL(CurrentStock.iQuantity,0)+ISNULL(CurrentStock.fInQuantity,0)-( pl.tqty-pl.tTakeNum-pl.tNonReQNum-pl.tReQNum-pl.tNonReMNum-pl.tReMNum) END AS TotAppNum FROM (SELECT mom_order.Moid,mom_order.MoCode,mom_order.CreateDate,mom_orderdetail.MoDid,mom_orderdetail.Qty,mom_orderdetail.WhCode, mom_orderdetail.QualifiedInQty,mom_orderdetail.BomId, mom_orderdetail.InvCode,inventory.cInvName AS momName,inventory.cInvStd as momStd,mom_orderdetail.RelsDate,mom_orderdetail.CloseDate FROM mom_order,mom_orderdetail ,inventory WHERE mom_orderdetail.status=‘3‘ AND mom_order.MOID=mom_orderdetail.MOID AND mom_orderDetail.InvCode=inventory.cInvcode) mom LEFT JOIN (SELECT Allocateid,MODID,Qty AS listQty,IssQty,WhCode,InvCode AS listinvcode FROM mom_moallocate) list ON mom.MODID=list.MODID LEFT JOIN Inventory ON list.listInvCode=Inventory.cInvCode LEFT JOIN (SELECT al.invcode as tinvcode,SUM(al.QTY) AS TQTY,SUM(al.IssQty) AS TIssQty ,SUM(NonTakeNum) AS tNonTakeNum,SUM(TakeNum) AS tTakeNum, SUM(NonReQNum) AS tNonReQNum,SUM(ReQNum) AS tReQNum,SUM(NonReMNum) AS tNonReMNum,SUM(ReMNum) AS tReMNum FROM mom_moallocate al INNER JOIN mom_orderdetail od ON al.modid=od.modid AND od.status=‘3‘ LEFT JOIN (SELECT cinvcode,impoids, SUM(CASE WHEN iQuantity>0 AND cHandler IS NULL THEN iQuantity ELSE 0 END ) AS NonTakeNum, SUM(CASE WHEN iQuantity>0 AND cHandler IS NOT NULL THEN iQuantity ELSE 0 END ) AS TakeNum, SUM(CASE WHEN iQuantity<0 AND cRdCode=‘212‘ AND cHandler IS NULL THEN iQuantity ELSE 0 END) AS NonReQNum, SUM(CASE WHEN iQuantity<0 AND cRdCode=‘212‘ AND cHandler IS NOT NULL THEN iQuantityELSE 0 END) AS ReQNum, SUM(CASE WHEN iQuantity<0 AND cRdCode=‘208‘ AND cHandler IS NULL THEN iQuantity ELSE 0 END) AS NonReMNum, SUM(CASE WHEN iQuantity<0 AND cRdCode=‘208‘ AND cHandler IS NOT NULL THEN iQuantityELSE 0 END) AS ReMNum FROM rdrecord,rdrecords where rdrecord.cBusType=‘领料‘ AND rdrecord.id=rdrecords.id AND rdrecords.impoids >0 GROUP BY cinvCode,impoids)rdt ON al.allocateid=rdt.impoids AND al.invcode=rdt.cinvcode GROUP BY al.Invcode ) pl ON list.listinvcode=pl.tinvcode LEFT JOIN (SELECT cinvcode,impoids, SUM(CASE WHEN iQuantity>0 AND cHandler IS NULL THEN iQuantity ELSE 0 END ) AS NonTakeNum, SUM(CASE WHEN iQuantity>0 AND cHandler IS NOT NULL THEN iQuantity ELSE 0 END ) AS TakeNum, SUM(CASE WHEN iQuantity<0 AND cRdCode=‘212‘ AND cHandler IS NULL THEN iQuantity ELSE 0 END) AS NonReQNum, SUM(CASE WHEN iQuantity<0 AND cRdCode=‘212‘ AND cHandler IS NOT NULL THEN iQuantityELSE 0 END) AS ReQNum, SUM(CASE WHEN iQuantity<0 AND cRdCode=‘208‘ AND cHandler IS NULL THEN iQuantity ELSE 0 END) AS NonReMNum, SUM(CASE WHEN iQuantity<0 AND cRdCode=‘208‘ AND cHandler IS NOT NULL THEN iQuantityELSE 0 END) AS ReMNum FROM rdrecord,rdrecords where rdrecord.cBusType=‘领料‘ AND rdrecord.id=rdrecords.id AND rdrecords.impoids >0 GROUP BY cinvCode,impoids) rd ON list.Allocateid=rd.impoids AND list.listinvcode=rd.cinvcode LEFT JOIN CurrentStock ON list.listinvcode=CurrentStock.cInvCode AND CurrentStock.cWhcode in (‘M01‘,‘F01‘,‘BCP‘) AND CurrentStock.iQuantity>0 (25) 说明:显示文章、提交人和最后回复时间 说明:日程安排提前五分钟提醒 说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.) (26) --字符串函数 (27) 收缩数据库日志 (28) -- 获取M$ SQL Server用户表的字段信息 USE database1
SELECT
表名 = CASE a.colorder WHEN 1 THEN c.name ELSE ‘‘ END, 序 = a.colorder,
字段名 = a.name,
标识 = CASE COLUMNPROPERTY(a.id,a.name,‘IsIdentity‘) WHEN 1 THEN ‘√‘ ELSE ‘‘ END, 主键 = CASE WHEN EXISTS ( SELECT * FROM sysobjects
WHERE xtype=‘PK‘ AND name IN ( SELECT name
FROM sysindexes
WHERE id=a.id AND indid IN ( SELECT indid
FROM sysindexkeys
WHERE id=a.id AND colid IN ( SELECT colid
FROM syscolumns
WHERE id=a.id AND name=a.name ) ) ) ) THEN ‘√‘ ELSE ‘‘ END,
类型 = b.name,
字节数 = a.length,
长度 = COLUMNPROPERTY(a.id,a.name,‘Precision‘), 小数 = CASE ISNULL(COLUMNPROPERTY(a.id,a.name,‘Scale‘),0) WHEN 0 THEN ‘‘ ELSE CAST(COLUMNPROPERTY(a.id,a.name,‘Scale‘) AS VARCHAR) END,
允许空 = CASE a.isnullable WHEN 1 THEN ‘√‘ ELSE ‘‘ END, 默认值 = ISNULL(d.[text],‘‘), 说明 = ISNULL(e.[value],‘‘) FROM syscolumns a
LEFT JOIN systypes b ON a.xtype=b.xusertype INNER JOIN sysobjects c ON a.id=c.id AND c.xtype=‘U‘ AND c.name<>‘dtproperties‘ LEFT JOIN syscomments d ON a.cdefault=d.id LEFT JOIN sysproperties e ON a.id=e.id AND a.colid=e.smallid ORDER BY c.name, a.colorder (29) 免费视频: (30) 一年中所有为星期二的日期 (31) --排名子函数 select ROW_NUMBER() OVER (ORDER BY sum(amount)) ROW_NUMBER, Rank () OVER (ORDER BY sum(amount)) Rank , DENSE_RANK() OVER (ORDER BY sum(amount)) DENSE_RANK
--说明 ROW_NUMBER() OVER (ORDER BY sum(amount)) ROW_NUMBER,--行号 Rank () OVER (ORDER BY sum(amount)) Rank ,--可并列排名,并列后,排名跳号 DENSE_RANK() OVER (ORDER BY sum(amount)) DENSE_RANK --可并列排名,并列后,排名不跳号 (32) create table A( (33) CREATE function f_split(@SourceSql varchar(8000),@StrSeprate varchar(10)) returns @temp table(a varchar(100)) /*--实现split功能 的函数 */ as begin declare @i int set @SourceSql=rtrim(ltrim(@SourceSql)) set @i=charindex(@StrSeprate,@SourceSql) while @i>=1 begin insert @temp values(left(@SourceSql,@i-1)) set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i) set @i=charindex(@StrSeprate,@SourceSql) end if @SourceSql<>‘\‘ insert @temp values(@SourceSql) return end (34) /*--解决一段sql文字符串超过8000字符的问题 (35) declare @i int (36) 复制表结构,而不复制内容 (37) /*
功能:2000当中绘画日历 */
DECLARE @Year nvarchar(4) DECLARE @YearMonth nvarchar(7) --月份 DECLARE @strTop nvarchar(200) DECLARE @ForI INT,@ForYear INT ,@MaxDay INT DECLARE @RowX INT --行位置 DECLARE @strWeekDayList nvarchar(20) DECLARE @strPrint nvarchar(300) -- ======================================
SET @Year=‘2008‘ --请在这里输入年份 -- ======================================
SET @strTop= ‘日‘+char(9)+‘一‘+char(9)+‘二‘ +char(9)+‘三‘++char(9)+‘四‘++char(9)+‘五‘++char(9)+‘六‘ +char(13)+ ‘───────────────────────────‘
SET @strWeekDayList=‘日一二三四五六‘ SET @ForYear=1 WHILE @ForYear<=12 --1月份至12月份 BEGIN
SET @YearMonth=@Year + ‘-‘ +CAST( @ForYear AS nvarchar(2)) SET @MaxDay=DAY(DATEADD(Day,-1,DATEADD(Month,1,@YearMonth+‘-01‘))) SET @RowX=CHARINDEX(RIGHT(DATENAME(WeekDay,@YearMonth+‘-01‘),1),@strWeekDayList)-1 SET @strPrint=‘‘ SET @ForI=1 WHILE @ForI<=@RowX --构造1号的位置 BEGIN
SET @strPrint=@strPrint+CHAR(9) SET @ForI=@ForI+1 END
SET @ForI=1 WHILE @ForI<=@MaxDay --构造2号到月底的位置 BEGIN
SET @strPrint=@strPrint+CAST(@ForI AS nvarchar(2)) +Char(9) SET @RowX=@RowX+1 SET @ForI=@ForI+1 IF (@RowX%7=0) BEGIN
SET @RowX=0 SET @strPrint=@strPrint+CHAR(13) END
END
SET @ForYear=@ForYear+1 -- 打印输出一个月的结果 PRINT ‘━━━━━━━━━━━━━━━━━━━━━━━━━━━‘ PRINT +Char(9)++Char(9)+‘ ‘+@YearMonth+CHAR(10) PRINT @strTop PRINT @strPrint +CHAR(10) END
(38) /* SQL 2005当中绘画日历 */ Set Nocount On Declare @Date datetime, @StartDate datetime, @EndDate datetime, @FirstIndex int
Set @Date =‘20080222‘ --输入一个日期,即可算出当月的日历
Select @StartDate=Convert(char(6),@Date,112)+‘01‘, @EndDate=Dateadd(month,1,@StartDate)-1, @FirstIndex=Datediff(day,-1,@StartDate)%7
;With t As ( Select Date=Convert(int,1),Row=(@FirstIndex)/7,Col=@FirstIndex Union All Select Date=Date+1,Row=(@FirstIndex+Date)/7,Col=(Date+@FirstIndex)%7 From t Where Date<=Datediff(day,@StartDate,@EndDate) ) Select [日]=Isnull(Convert(char(2),[0]),‘‘), [一]=Isnull(Convert(char(2),[1]),‘‘), [二]=Isnull(Convert(char(2),[2]),‘‘), [三]=Isnull(Convert(char(2),[3]),‘‘), [四]=Isnull(Convert(char(2),[4]),‘‘), [五]=Isnull(Convert(char(2),[5]),‘‘), [六]=Isnull(Convert(char(2),[6]),‘‘) From t Pivot (Max(Date) For col In([0],[1],[2],[3],[4],[5],[6])) b
/* 2008年2月份 ------------ 日 一 二 三 四 五 六 ---- ---- ---- ---- ---- ---- ---- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 */ (39) 轉發一個日期列轉行的,作者:pt1314917 背着灵魂漫步 (40) [url=http://topic.csdn.net/u/20081106/11/1141518b-05af-4843-b85d-93db9b484fea.html]http://topic.csdn.net/u/20081106/11/1141518b-05af-4843-b85d-93db9b484fea.html SQL code create function GetFormatString(@dec decimal(28,8), @n int) returns varchar(32) as begin declare @str varchar(32), @len int, @left varchar(32), @right varchar(32),@endvarchar(32) if @n!=‘0‘ BEGIN
set @str= round(@dec,@n) select @left=left(@str,charindex(‘.‘,@str)-1),@len=len(@left)-2 while @len>1 begin select @left=stuff(@left,@len,0,‘,‘), @len=@len-3 end select @right=left(stuff(@str,1,charindex(‘.‘,@str),‘‘), @n),@len=4 while @len <=len(@right) begin select @right=stuff(@right,@len,0,‘,‘), @len=@len+4 end set @end= @left+‘.‘+@right end else BEGIN
set @str= round(@dec,@n) select @left=left(@str,charindex(‘.‘,@str)-1),@len=len(@left)-2 while @len>1 begin select @left=stuff(@left,@len,0,‘,‘), @len=@len-3 end select @right=left(stuff(@str,1,charindex(‘.‘,@str),‘‘), @n),@len=4 while @len <=len(@right) begin select @right=stuff(@right,@len,0,‘,‘), @len=@len+4 end set @end= @left end return @end end
select dbo.GetFormatString(123645.7889, 2)+‘±‘+‘MON‘ union all select dbo.GetFormatString(123645.7889, 3)+‘±‘+‘MON‘ union all select dbo.GetFormatString(123645.7889, 4)+‘±‘+‘MON‘ (41) 1.给一条得到任意月份的是大天数 SQL code
use master go
if exists(select 1 from dbo.sysobjects where name=‘SP_select_t‘ and xtype=‘P‘) drop proc SP_select_t go
CREATE proc SP_select_t(@Tablename sysname) as exec(‘Select top 30 * from ‘+@Tablename+‘ Order by 1 desc‘) go
if exists(select 1 from dbo.sysobjects where name=‘SP_HelpTable‘ and xtype=‘P‘) drop proc SP_HelpTable go
create proc SP_HelpTable(@TableName varchar(20)) as if not exists (select 1 from sysobjects where name=@tableName and Xtype=‘U‘) begin Select ‘No Table Name is‘+@TableName as Error Return end
SELECT 表名=case when a.colorder=1 then d.name else ‘‘ end, 字段名=a.name, --标识=case when COLUMNPROPERTY( a.id,a.name,‘IsIdentity‘)=1 then ‘√‘else ‘‘ end, /*主键=case when exists(SELECT 1 FROM sysobjects where xtype=‘PK‘ and name in ( SELECT name FROM sysindexes WHERE indid in( SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid ))) then ‘√‘ else ‘‘ end, */ 类型=b.name, --占用字节数=a.length, 长度=COLUMNPROPERTY(a.id,a.name,‘PRECISION‘), 小数位数=isnull(COLUMNPROPERTY(a.id,a.name,‘Scale‘),0), 允许空=case when a.isnullable=1 then ‘√‘else ‘‘ end, 默认值=isnull(e.text,‘‘), 字段序号=a.colorder, 字段说明=isnull(g.[value],‘‘) FROM syscolumns a left join systypes b on a.xtype=b.xusertype inner join sysobjects d on a.id=d.id and d.xtype=‘U‘ and d.name<>‘dtproperties‘ left join syscomments e on a.cdefault=e.id left join sysproperties g on a.id=g.id and a.colid=g.smallid
where d.name=@TableName order by a.id,a.colorder Exec sp_helpIndex @tablename
go (42) 下列语句部分是Mssql语句,不可以在access中使用。 不必写出RNumber 和ID,你只需要检查匹配情况即可。只要你对以上代码的工作满意,你自可按需操作“随机”记录。Recordset没有包含其他内容,因此你很快就能找到你需要的记录这样就大大降低了处理时间。 (44) Create FUNCTION [dbo].[ID15TO18] (@id15 char(15)) /*功能:将身份证的15位号码升级为18位
-- -- --调用函数 -- update -- 表 -- set -- 身份证号 = dbo.ID15TO18(身份证号) -- where -- LEN(身份证号) = 15 -- -- */ RETURNS CHAR(18) AS BEGIN DECLARE @ID18 CHAR(18)
DECLARE @S1 AS INTEGER DECLARE @S2 AS INTEGER DECLARE @S3 AS INTEGER DECLARE @S4 AS INTEGER DECLARE @S5 AS INTEGER DECLARE @S6 AS INTEGER DECLARE @S7 AS INTEGER DECLARE @S8 AS INTEGER DECLARE @S9 AS INTEGER DECLARE @S10 AS INTEGER DECLARE @S11 AS INTEGER DECLARE @S12 AS INTEGER DECLARE @S13 AS INTEGER DECLARE @S14 AS INTEGER DECLARE @S15 AS INTEGER DECLARE @S16 AS INTEGER DECLARE @S17 AS INTEGER DECLARE @S18 AS INTEGER
SET @S1=SUBSTRING(@ID15,1,1) SET @S2=SUBSTRING(@ID15,2,1) SET @S3=SUBSTRING(@ID15,3,1) SET @S4=SUBSTRING(@ID15,4,1) SET @S5=SUBSTRING(@ID15,5,1) SET @S6=SUBSTRING(@ID15,6,1) SET @S7=1 SET @S8=9 SET @S9=SUBSTRING(@ID15,7,1) SET @S10=SUBSTRING(@ID15,8,1) SET @S11=SUBSTRING(@ID15,9,1) SET @S12=SUBSTRING(@ID15,10,1) SET @S13=SUBSTRING(@ID15,11,1) SET @S14=SUBSTRING(@ID15,12,1) SET @S15=SUBSTRING(@ID15,13,1) SET @S16=SUBSTRING(@ID15,14,1) SET @S17=SUBSTRING(@ID15,15,1)
SET @S18=((@S1*7)+(@S2*9)+(@S3*10)+(@S4*5)+(@S5*8)+(@S6*4)+(@S7*2)+(@S8*1) +(@S9*6)+(@S10*3)+(@S11*7)+(@S12*9)+(@S13*10)+(@S14*5)+(@S15*8)+(@S16 *4)+(@S17*2))%11
SET @ID18=SUBSTRING(@ID15,1,6)+‘19‘+SUBSTRING(@ID15,7,9) +CASE WHEN @S18=0 THEN ‘1‘ WHEN @S18=1 THEN ‘0‘ WHEN @S18=2 THEN ‘X‘ WHEN @S18=3 THEN ‘9‘ WHEN @S18=4 THEN ‘8‘ WHEN @S18=5 THEN ‘7‘ WHEN @S18=6 THEN ‘6‘ WHEN @S18=7 THEN ‘5‘ WHEN @S18=8 THEN ‘4‘ WHEN @S18=9 THEN ‘3‘ WHEN @S18=10 THEN ‘2‘ END
RETURN @ID18 END (45) Create FUNCTION [dbo].[f_digit_chn](@num bigint) RETURNS varchar(20) AS BEGIN --将整型数字转换为大写汉字的自定义函数,如123084转换为‘壹贰叁零捌肆‘ -- 调用 select dbo.[f_digit_chn](12345678) DECLARE @result varchar(20),@symbol varchar(2) IF @num<0 SELECT @symbol=‘负‘,@result=‘‘,@num=ABS(@num) ELSE SELECT @symbol=‘‘,@result=‘‘ WHILE @num<>0 SELECT @result=SUBSTRING(‘零壹贰叁肆伍陆柒捌玖拾‘,@num%10+1,1)+@result,@num=@num/10 RETURN @symbol+@result END (46)
( @metabname varchar(200), --表名 @mepagesize int, --每页显示记录数 @mepageint int, --分页条显示个数 @thispage int, --当前页编号
@msrsall int output, --总记录数 @mspagecount int output --总页数 ) AS declare @tabsql nvarchar(200) declare @pagecount int --分页总数 declare @rsall int --总记录数 declare @top int --提当前段数据 declare @sql varchar(200) ------------------------------------------------------------------------------------ set @tabsql=‘select @rsall =count(*) from ‘+ @metabname exec sp_executesql @tabsql,N‘@rsall int output‘,@rsall output ------------------------------------------------------------------------------------ if @rsall >0 --有数据 begin set @top=@mepagesize*(@thispage-1) set @sql=‘select top ‘ + str(@mepagesize) + ‘ * from ‘+@metabname+‘ where id not in(select top ‘+ str(@top) +‘ id from ‘+@metabname+‘) order by id asc‘ exec(@sql) if @rsall % @mepagesize=0 begin set @pagecount=@rsall / @mepagesize end else begin set @pagecount=@rsall / @mepagesize+1 end end else --没数据 begin set @msrsall=0 set @mspagecount=0 end set @msrsall=@rsall --总信息数 set @mspagecount=@pagecount --分页总数 GO (47) 存储过程如下: (48) --行列转换示例--列变行 (49) --查所有加入域的人的信息 SELECT sAMAccountname AS AccountName, GivenName AS [First Name], SN AS [Last Name], mail AS [E-mail Address], TelephoneNumber AS [Telephone Number], l AS Office, PostalAddress AS [Postal Address], PostalCode, StreetAddress AS [Street Address], wWWHomePage AS [Web Page], distinguishedname AS DN FROM OPENQUERY( ADSI, ‘SELECT GivenName, SN, company, department, TelephoneNumber, mail, distinguishedname, title, l, manager, mobile, name, PhysicalDeliveryOfficeName, PostalAddress, PostalCode, sAMAccountname, StreetAddress, wWWHomePage FROM ‘‘LDAP://itg.net/ OU=itg ,DC=itg,DC=net‘‘ WHERE objectCategory = ‘‘Person‘‘ AND objectClass = ‘‘user‘‘ ORDER BY Name‘ ) Rowset_1
--where sAMAccountname =‘clw‘ --查个人信息
--查部门信息
SELECT * FROM OPENQUERY( ADSI, ‘SELECT GivenName, SN, company, department, TelephoneNumber, mail, distinguishedname, title, l, manager, mobile, name, PhysicalDeliveryOfficeName, PostalAddress, PostalCode, sAMAccountname, StreetAddress, wWWHomePage FROM ‘‘LDAP://itg.net/ OU=itg ,DC=itg,DC=net‘‘ WHERE objectCategory = ‘‘Person‘‘ AND objectClass = ‘‘user‘‘ ORDER BY Name‘ ) Rowset_1
where distinguishedname like ‘%OU=财务部,%‘ --查IT部门的域信息 (50) 我来加一个,用代码实现在SqlServer2005上布置一个job USE [msdb] GO /****** Object: StoredProcedure [dbo].[sp_create_job] Script Date: 02/10/2009 19:44:33 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER OFF GO
create proc [dbo].[sp_create_job]
as
BEGIN TRANSACTION DECLARE @jobLogpath VARCHAR(1000) DECLARE @JobID BINARY(16) DECLARE @ReturnCode INT SELECT @ReturnCode = 0 IF (SELECT COUNT(*) FROM msdb.dbo.syscategories WHERE name = N‘[Uncategorized (Local)]‘) < 1 EXECUTE msdb.dbo.sp_add_category @name = N‘[Uncategorized (Local)]‘
-- Delete the job with the same name (if it exists) SELECT @JobID = job_id FROM msdb.dbo.sysjobs WHERE (name = N‘FiveDayOptOutList‘) IF (@JobID IS NOT NULL) BEGIN -- Check if the job is a multi-server job IF (EXISTS (SELECT * FROM msdb.dbo.sysjobservers WHERE (job_id = @JobID) AND (server_id <> 0))) BEGIN -- There is, so abort the script RAISERROR (N‘Unable to import job ‘‘FiveDayOptOutList‘‘ since there is already a multi-server job with this name.‘, 16, 1) GOTO QuitWithRollback END ELSE -- Delete the [local] job EXECUTE msdb.dbo.sp_delete_job @job_name = N‘FiveDayOptOutList‘ SELECT @JobID = NULL END
BEGIN /*****************************************************************************************************/ DEClARE @ServerRole Varchar(20) DECLARE @UserName Varchar(20) DECLARE @Logfile_name Varchar(100) ------------------------------------------------------------------------------------------------------- if object_id(‘msdb.dbo.temppopedom‘) is not null drop table msdb.dbo.temppopedom ------------------------------------------------------------------------------------------------------- /***select all users information in SqLServer **/ select SrvRole = g.name, UserName = u.name, MemberSID = u.sid into msdb.dbo.temppopedom from sys.server_principals u, sys.server_principals g, sys.server_role_members m where g.principal_id = m.role_principal_id and u.principal_id = m.member_principal_id order by 1, 2 ------------------------------------------------------------------------------------------------------- /***select the user‘s name who using database currently **/ select @UserName = loginame from master.dbo.sysprocesses where uid=user_id() ------------------------------------------------------------------------------------------------------- /***select the user‘s role who using database currently base on @UserName **/ select @ServerRole=SrvRole from msdb.dbo.temppopedom where Username=@UserName ------------------------------------------------------------------------------------------------------- /*****************************************************************************************************/
-- Add the job EXECUTE @ReturnCode = msdb.dbo.sp_add_job @job_id = @JobID OUTPUT , @job_name = N‘FiveDayOptOutList‘, @owner_login_name = @UserName, @description = N‘Execute package: FiveDayOptOutList‘, @category_name = N‘[Uncategorized (Local)]‘, @enabled = 1, @notify_level_email = 0, @notify_level_page = 0, @notify_level_netsend = 0, @notify_level_eventlog = 2, @delete_level= 0 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback ------------------------------------------------------------------------ IF @ServerRole = N‘sysadmin‘ BEGIN -- SysAdmin role Add the job steps EXECUTE @ReturnCode = msdb.dbo.sp_add_jobstep @job_id = @JobID, @step_name = N‘CREATE TABLE ‘, @step_id = 1, @cmdexec_success_code = 0, @on_success_action = 1, @on_success_step_id = 0, @on_fail_action = 2, @on_fail_step_id=0, @retry_attempts = 0, @retry_interval = 0, @os_run_priority=0, @subsystem = N‘CmdExec‘, @command=N‘input you commond ‘, @output_file_name = @jobLogpath, @server = N‘‘, @database_user_name = N‘‘, @flags = 4 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N‘FiveDayOptOutList‘, @enabled=1, @freq_type=8, @freq_interval=2, @freq_subday_type=1, @freq_subday_interval=0, @freq_relative_interval=1, @freq_recurrence_factor=1, @active_start_date=20070319, @active_end_date=99991231, @active_start_time=230000, @active_end_time=235959 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback --EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N‘(local)‘ --IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback END ELSE ---non-SysAdmin Role add job ---------------------------------- EXECUTE @ReturnCode = msdb.dbo.sp_add_jobstep @job_id = @JobID, @step_name = N‘CREATE TABLE ‘, @step_id = 1, @cmdexec_success_code = 0, @on_success_action = 1, @on_success_step_id = 0, @on_fail_action = 2, @on_fail_step_id=0, @retry_attempts = 0, @retry_interval = 0, @os_run_priority=0, @subsystem = N‘CmdExec‘, @command=N‘input you commond ‘, @server = N‘‘, @flags = 16 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N‘FiveDayOptOutList‘, @enabled=1, @freq_type=8, @freq_interval=2, @freq_subday_type=1, @freq_subday_interval=0, @freq_relative_interval=1, @freq_recurrence_factor=1, @active_start_date=20070319, @active_end_date=99991231, @active_start_time=230000, @active_end_time=235959 IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N‘(local)‘ IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
END ----------------------- COMMIT TRANSACTION GOTO EndSave QuitWithRollback: IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION EndSave: (51) c++截取字符串前后指定字符的函数 C/C++ code
TCHAR *TrimLeft(TCHAR *str, TCHAR *sep = _T(" \t\n")); TCHAR *Trim(TCHAR *str, TCHAR *sep = _T(" \t\n")); TCHAR *TrimRight(TCHAR *str, TCHAR *sep = _T(" \t\n"));
TCHAR *Trim(TCHAR *str, TCHAR *sep) { return TrimLeft(TrimRight(str, sep), sep); }
TCHAR *TrimLeft(TCHAR *str, TCHAR *sep) { TCHAR *pstr = str; for (; *pstr != 0; pstr++) { TCHAR *p = sep; while (*p != 0 && *p != *pstr) p++; if (*p == 0) break; } if (pstr > str) _tcscpy(str, pstr);
return str; }
TCHAR *TrimRight(TCHAR *str, TCHAR *sep) { TCHAR *pstr = str + _tcslen(str) - 1;
for (; pstr >= str; pstr--) { TCHAR *p = sep; while (*p != 0 && *p != *pstr) p++; if (*p == 0) break; } pstr[1] = 0;
return str; } (52) sql中的循环: (53) 随机查询语句,随机返回表中的n条记录 (54) 看一段 邹老大的实战代码——乘车模型 SQL code
CREATE TABLE T_Line( ID nvarchar(10), -- 公交线路号 Station nvarchar(10), -- 站点名称 Orders int) -- 行车方向(通过它反应每个站的上一个、下一个站) INSERT T_Line SELECT N‘8路‘ ,N‘站A‘, 1 UNION ALL SELECT N‘8路‘ ,N‘站B‘, 2 UNION ALL SELECT N‘8路‘ ,N‘站C‘, 3 UNION ALL SELECT N‘8路‘ ,N‘站D‘, 4 UNION ALL SELECT N‘8路‘ ,N‘站J‘, 5 UNION ALL SELECT N‘8路‘ ,N‘站L‘, 6 UNION ALL SELECT N‘8路‘ ,N‘站M‘, 7 UNION ALL SELECT N‘20路‘ ,N‘站G‘, 1 UNION ALL SELECT N‘20路‘ ,N‘站H‘, 2 UNION ALL SELECT N‘20路‘ ,N‘站I‘, 3 UNION ALL SELECT N‘20路‘ ,N‘站J‘, 4 UNION ALL SELECT N‘20路‘ ,N‘站L‘, 5 UNION ALL SELECT N‘20路‘ ,N‘站M‘, 6 UNION ALL SELECT N‘255路‘,N‘站N‘, 1 UNION ALL SELECT N‘255路‘,N‘站O‘, 2 UNION ALL SELECT N‘255路‘,N‘站P‘, 3 UNION ALL SELECT N‘255路‘,N‘站Q‘, 4 UNION ALL SELECT N‘255路‘,N‘站J‘, 5 UNION ALL SELECT N‘255路‘,N‘站D‘, 6 UNION ALL SELECT N‘255路‘,N‘站E‘, 7 UNION ALL SELECT N‘255路‘,N‘站F‘, 8 GO
-- 乘车线路查询存储过程 CREATE PROC dbo.p_qry @Station_Start nvarchar(10), @Station_Stop nvarchar(10) AS SET NOCOUNT ON DECLARE @l int SET @l = 0
-- a. 从开始站点查询可能的乘车线路 SELECT ID, Station, Line = CONVERT(nvarchar(4000), ‘(‘ + RTRIM(ID) + ‘: ‘ + RTRIM(Station)), Orders = Orders, [Level] = @l INTO # FROM T_Line WHERE Station = @Station_Start
-- 循环查找所有可能线路, 直到找不到可用线路或者找到达到终止站点的乘车线路 WHILE @@ROWCOUNT > 0 AND NOT EXISTS( SELECT * FROM # WHERE Station = @Station_Stop) BEGIN SET @l = @l + 1 INSERT #( Line, ID, Station, Orders, [Level]) SELECT Line = A.Line + CASE WHEN A.ID = B.ID THEN N‘->‘ + RTRIM(B.Station) ELSE N‘) ∝ (‘ + RTRIM(B.ID) + N‘: ‘ + RTRIM(B.Station) END, B.ID, B.Station, B.Orders, @l FROM # A, T_Line B WHERE A.[Level] = @l - 1 AND( (A.Station = B.Station AND A.ID <> B.ID) -- 另一条统一口径 OR ( A.ID = B.ID -- 同一站点的前一站或者下一站 AND( A.Orders = B.Orders + 1 OR A.Orders = B.Orders - 1) ) ) AND LEN(A.Line) < 4000 -- 避免查找已经找过的线路 AND PATINDEX(‘%[ >]‘ + B.Station + ‘[-)]%‘, A.Line) = 0 END
-- 显示结果 SELECT N‘起点站‘ = @Station_Start, N‘终点站‘ = @Station_Stop, N‘乘车线路‘ = Line+N‘)‘ FROM # WHERE [Level] = @l AND Station = @Station_Stop IF @@ROWCOUNT = 0 --如果未有可以到达的线路,则显示处理结果表备查 SELECT * FROM # GO (55) 保留名次: (56) SQL codeDECLARE @dt datetime (57) 问题描述: (58)http://topic.csdn.net/u/20090310/17/0b8f60c5-9304-4633-84fa-d176f282cb7d.html 【SQL Server 数据库导入导出部分】 (59) 【SQL SERVER 数据库实用SQL语句】 (60) 【关闭SQL Server 数据库所有使用连接】 (61) Transact-SQL语句进行导入导出:
1.在SQL SERVER里查询access数据:
-- ======================================================
SELECT * FROM OpenDataSource( ‘Microsoft.Jet.OLEDB.4.0‘, ‘Data Source="c:\DB.mdb";User ID=Admin;Password=‘)...表名
-------------------------------------------------------------------------------------------------
2.将access导入SQL server
-- ======================================================
在SQL SERVER 里运行: SELECT * INTO newtable
FROM OPENDATASOURCE (‘Microsoft.Jet.OLEDB.4.0‘, ‘Data Source="c:\DB.mdb";User ID=Admin;Password=‘ )...表名
-------------------------------------------------------------------------------------------------
3.将SQL SERVER表里的数据插入到Access表中
-- ======================================================
在SQL SERVER 里运行: insert into OpenDataSource( ‘Microsoft.Jet.OLEDB.4.0‘, ‘Data Source=" c:\DB.mdb";User ID=Admin;Password=‘)...表名
(列名1,列名2) select 列名1,列名2 from sql表 实例: insert into OPENROWSET(‘Microsoft.Jet.OLEDB.4.0‘, ‘C:\db.mdb‘;‘admin‘;‘‘, Test) select id,name from Test INSERT INTO OPENROWSET(‘Microsoft.Jet.OLEDB.4.0‘, ‘c:\trade.mdb‘; ‘admin‘; ‘‘, 表名) SELECT * FROM sqltablename
-------------------------------------------------------------------------------------------------
二、SQL SERVER 和EXCEL的数据导入导出 1、在SQL SERVER里查询Excel数据:
-- ======================================================
SELECT * FROM OpenDataSource( ‘Microsoft.Jet.OLEDB.4.0‘, ‘Data Source="c:\book1.xls";User ID=Admin;Password=;Extended properties=Excel 5.0‘)...[Sheet1$] 下面是个查询的示例,它通过用于 Jet 的 OLE DB 提供程序查询 Excel 电子表格。 SELECT * FROM OpenDataSource ( ‘Microsoft.Jet.OLEDB.4.0‘, ‘Data Source="c:\Finance\account.xls";User ID=Admin;Password=;Extended properties=Excel 5.0‘)...xactions
-------------------------------------------------------------------------------------------------
2、将Excel的数据导入SQL server :
-- ======================================================
SELECT * into newtable FROM OpenDataSource( ‘Microsoft.Jet.OLEDB.4.0‘, ‘Data Source="c:\book1.xls";User ID=Admin;Password=;Extended properties=Excel 5.0‘)...[Sheet1$] 实例: SELECT * into newtable FROM OpenDataSource( ‘Microsoft.Jet.OLEDB.4.0‘, ‘Data Source="c:\Finance\account.xls";User ID=Admin;Password=;Extended properties=Excel 5.0‘)...xactions
-------------------------------------------------------------------------------------------------
3、将SQL SERVER中查询到的数据导成一个Excel文件
-- ======================================================
T-SQL代码:
EXEC master..xp_cmdshell ‘bcp 库名.dbo.表名out c:\Temp.xls -c -q -S"servername" -U"sa" -P""‘ 参数:S 是SQL服务器名;U是用户;P是密码 说明:还可以导出文本文件等多种格式 实例:EXEC master..xp_cmdshell ‘bcp saletesttmp.dbo.CusAccount out c:\temp1.xls -c -q -S"pmserver" -U"sa" -P"sa"‘ EXEC master..xp_cmdshell ‘bcp "SELECT au_fname, au_lname FROM pubs..authors ORDER BY au_lname" queryout C:\ authors.xls -c -Sservername -Usa -Ppassword‘ 在VB6中应用ADO导出EXCEL文件代码: Dim cn As New ADODB.Connection
cn.open "Driver={SQL Server};Server=WEBSVR;DataBase=WebMis;UID=sa;WD=123;" cn.execute "master..xp_cmdshell ‘bcp "SELECT col1, col2 FROM 库名.dbo.表名" queryout E:\DT.xls -c -Sservername -Usa -Ppassword‘" ------------------------------------------------------------------------------------------------
4、在SQL SERVER里往Excel插入数据:
-- ======================================================
insert into OpenDataSource( ‘Microsoft.Jet.OLEDB.4.0‘, ‘Data Source="c:\Temp.xls";User ID=Admin;Password=;Extended properties=Excel 5.0‘)...table1 (A1,A2,A3) values (1,2,3) T-SQL代码:
INSERT INTO OPENDATASOURCE(‘Microsoft.JET.OLEDB.4.0‘, ‘Extended Properties=Excel 8.0;Data source=C:\training\inventur.xls‘)...[Filiale1$] (bestand, produkt) VALUES (20, ‘Test‘) -------------------------------------------------------------------------------------------------
总结:利用以上语句,我们可以方便地将SQL SERVER、ACCESS和EXCEL电子表格软件中的数据进行转换,为我们提供了极大方便! EXEC master..xp_cmdshell ‘bcp "select OrderID,ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry from Northwind.dbo.orders" queryout "d:\Oreders.txt" -t"|" -c -q -S"127.0.0.1" -U"sa" -P""‘ SELECT * FROM OpenDataSource(‘Microsoft.Jet.OLEDB.4.0‘,‘Data Source="xxxx.xls";Extended Properties="Excel 8.0";IMEX=1;Persist Security Info=False‘)...[a1$] (62) 1. 分页查询数据 (63) --设置 min server memory 配置项 EXEC sp_configure N‘min server memory (MB)‘, 0
--设置 max server memory 配置项 EXEC sp_configure N‘max server memory (MB)‘, 256
--使更新生效 RECONFIGURE WITH OVERRIDE /*--功能说明
下面的代码是在SQL Server 2000上创建名为 MyDB 的数据库 该数据库包括1个主要数据文件、3个用户定义的文件组和1个日志文件 ALTER DATABASE语句将用户定义文件组指定为默认文件组。 之后,通过指默认的文件组来创建表,并且将图像数据和索引放到指定的文件组中。 最后,将文件组中的指定数据文件删除 --*/
--切换到 master 数据库 USE master GO
--A. 创建数据库 MyDB CREATE DATABASE MyDB ON PRIMARY --主文件组和主要数据文件 ( NAME=‘MyDB_Primary‘, FILENAME= ‘c:\MyDB_Prm.mdf‘), FILEGROUP MyDB_FG1 --用户定义文件组1 ( NAME = ‘MyDB_FG1_Dat1‘, FILENAME = ‘c:\MyDB_FG1_1.ndf‘), --次要数据文件1 ( NAME = ‘MyDB_FG1_Dat2‘, FILENAME = ‘d:\MyDB_FG1_2.ndf‘), --次要数据文件2 FILEGROUP MyDB_FG2 --用户定义文件组2 ( NAME = ‘MyDB_FG1_Dat‘, FILENAME = ‘e:\MyDB_FG2.ndf‘) --次要数据文件 LOG ON --日志文件 ( NAME=‘MyDB_log‘, FILENAME =‘d:\MyDB.ldf‘) GO
--B. 修改默认数据文件组 ALTER DATABASE MyDB MODIFY FILEGROUP MyDB_FG1 DEFAULT GO
--切换到新建的数据库 MyDB USE MyDB
--C. 在默认文件组MyDB_FG1创建表,并且指定图像数据保存在用户定义文件组MMyDB_FG2 CREATE TABLE MyTable ( cola int PRIMARY KEY , colb char(8) , colc image ) TEXTIMAGE_ON MyDB_FG2
--在用户定义文件组MyDB_FG2上创建索引 CREATE INDEX IX_MyTable ON MyTable(cola) ON MyDB_FG2 GO
--D. 将要删除数据文件MyDB_FG1_Dat1上的数据转移到其他数据文件中,并且清空数据文件MyDB_FG1_Dat1 DBCC SHRINKFILE(MyDB_FG1_Dat1,EMPTYFILE) --删除数据文件MyDB_FG1_Dat1 ALTER DATABASE MyDB REMOVE FILE MyDB_FG1_Dat1
--A. 将tempdb数据库的主数据文件大小设置为10MB。 ALTER DATABASE tempdb MODIFY FILE( name=tempdev, size=100 MB) GO
--B. 将tempdb数据库的主数据文件移动到指定的磁盘分区上,并且为其添加一个数据文件。 --移动主数据文件 ALTER DATABASE tempdb MODIFY FILE ( NAME=‘tempdev‘, FILENAME =‘d:\tempdb.mdf‘)
--添加次要数据文件 ALTER DATABASE tempdb ADD FILE ( NAME=‘tempdata_1‘, FILENAME =‘d:\tempdb_data_1.ndf‘)
(64) 1.sql 导出到 access (65) 【SQL Server 数据库常用函数使用】 (66) 查询数据库中所有的用户表的记录数以及其他 (67) sql 拼音查询
|
标签:
原文地址:http://blog.csdn.net/qq_16769857/article/details/51860016