declare @x varchar(8000) set @x='' select @x=@x+sp+' ' from table order by id set @x=left(@x,len(@x)-1) select @x
declare @t table(id int,sp nvarchar(20)) insert into @t select 1,'苹果' union all select 2,'香蕉' union all select 3,'桔子' select * from @tdeclare @c varchar(8000) set @c='' select @c = @c + ' '+sp from @t select @c
有不用存储过程的吗?因为是在程序中自动组合sql语句。另如果需要指定分隔符如‘*’该如何求解?
declare @x varchar(8000) set @x='' select @x=@x+ '*'+ sp from table order by id select @x --另:一句话的恐怕没有
对如果是空格要加一句 set @x=left(@x,len(@x)) 是*要加 set @x=left(@x,len(@x)-1)
create function test() returns varchar(8000) as begin declare @x varchar(8000) set @x='' select @x=@x+ ' '+ sp from table order by id return @x end然后就可以 select dbo.test()
注意: left(@x,len(@x)-1)的写法会在没有记录的时候出错。 当然你可以判断@x是否等于''你可以使用substring()就不需要做判断都可以了,代码如下: declare @x varchar(8000) set @x='' select @x=@x + ' ' + sp from @t order by id set @x=substring(@x,2,8000) select @x有不用存储过程的吗?因为是在程序中自动组合sql语句。 ---- 存储过程是可以,还是函数方便,写法可以是: create function test() returns varchar(8000) as begin declare @x varchar(8000) set @x='' select @x=@x + ' ' + sp from @t order by id set @x=substring(@x,2,8000) return @x end -- 前台调用: sql = "select dbo.test()"
结果只能在一个字段中。 ------------------------------ 这是一个有趣的现象。大家都能把这句话理解成“结果放到一行中”。而不会理解成: select sp from tablename
set @x=''
select @x=@x+sp+' ' from table order by id
set @x=left(@x,len(@x)-1)
select @x
insert into @t select 1,'苹果' union all select 2,'香蕉' union all select 3,'桔子'
select * from @tdeclare @c varchar(8000)
set @c=''
select @c = @c + ' '+sp from @t
select @c
set @x=''
select @x=@x+ '*'+ sp from table order by id
select @x
--另:一句话的恐怕没有
set @x=left(@x,len(@x))
是*要加
set @x=left(@x,len(@x)-1)
returns varchar(8000)
as
begin
declare @x varchar(8000)
set @x=''
select @x=@x+ ' '+ sp from table order by id
return @x
end然后就可以
select dbo.test()
left(@x,len(@x)-1)的写法会在没有记录的时候出错。
当然你可以判断@x是否等于''你可以使用substring()就不需要做判断都可以了,代码如下:
declare @x varchar(8000)
set @x=''
select @x=@x + ' ' + sp from @t order by id
set @x=substring(@x,2,8000)
select @x有不用存储过程的吗?因为是在程序中自动组合sql语句。
----
存储过程是可以,还是函数方便,写法可以是:
create function test()
returns varchar(8000)
as
begin
declare @x varchar(8000)
set @x=''
select @x=@x + ' ' + sp from @t order by id
set @x=substring(@x,2,8000)
return @x
end
-- 前台调用:
sql = "select dbo.test()"
------------------------------
这是一个有趣的现象。大家都能把这句话理解成“结果放到一行中”。而不会理解成:
select sp from tablename