SQL 合并行,返回带分隔字符的字符串
--合并行,并返回合并的值
Create proc [dbo].[proUniteRow]
@tab varchar(30), --表名
@col varchar(30), --合并的列名
@where varchar(2000), --合并的条件
@firstSplit varchar(100), --连接字符前缀
@lastSplit varchar(100), --连接字符后缀
@order varchar(100), --排序
@val nvarchar(2000)='' output –返回值
as
begin
declare @sql nvarchar(2000)
set @sql='
declare @retStr varchar(2000)
set @retStr=''''
declare cur cursor
read_only
for select
'+@col+' from '+@tab
if len(@where)>0
set @sql=@sql+' where '+@where
if len(@order)>0
set @sql=@sql+' order by '+@order
set @sql=@sql+'
declare @str varchar(2000)
open cur
fetch next from cur into @str
while (@@fetch_status =0)
begin
set @retStr=@retStr+'''+@firstSplit+'''+@str+'''+@lastSplit+'''
fetch next from cur into @str
end
close cur
deallocate cur
if len(@retStr)>0
set @strEnd=substring(@retStr,1,len(@retStr)-1)
'
exec sp_executesql @sql,N'@strEnd nvarchar(2000) output',@val output
end
执行:
表pro_lbsxb:
ID lbsx_value lbsx_isList lbsx_order
1 A 1 1
2 B 1 2
3 C 1 3
4 D &
相关文档:
Student(S#,Sname,Sage,Ssex) 学生表
Course(C#,Cname,T#) 课程表
SC(S#,C#,score) 成绩表
Teacher(T#,Tname) 教师表
问题:
1、查询“001”课程比“002”课程成绩高的所有学生的学号;
select a.S# from (select s#,score from SC where C#='001') a,(select s#,score
fr ......
-----------------------------------------------------------------------------------------------------------------------
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 i ......
if not object_id('Tempdb..#T') is null
drop table #T
Go
Create table #T([ID] int,[Name] nvarchar(1),[Memo] nvarchar(2))
Insert #T
select 1,N'A',N'A1' union all
select 2,N'A',N'A2' union all
select 3,N'A',N'A3' union all
select 4,N'B',N'B1' union all
select 5,N'B',N'B2'
G ......
分页查询的原理:
这个只能用再Sql2005及以上的版本
DECLARE @pagenum AS INT, @pagesize AS INT
SET @pagenum = 2
SET @pagesize = 3
SELECT *
from (SELECT ROW_NUMBER()&n ......