简单SQL Server问题
发布网友
发布时间:2023-05-27 05:45
我来回答
共2个回答
热心网友
时间:2024-12-13 10:04
这个我想还是比较好写的,用游标滚一下就好了。我在实际客户需求中遇到的与你的题目恰恰相反,不过更简单,一条动态sql就搞定了。
这题答案如下:
Create Procere ReturnStr
(
@Patten Varchar(4)--传入类型
)
As
Begin
Declare @D_D Varchar(10),@Str_D Varchar(100)
Declare @Num_D Int,@I_D Int
Set @D_D = '';
Set @Str_D = '';
Set @Num_D = 0;
Set @I_D = 0;
Select 'D1' As j Into #Temp
Union Select 'D2'
Union Select 'D3'
Union Select 'D4';
Select @Num_D = Count(*) From #Temp;
DECLARE Temp_Cursor CURSOR FOR
SELECT j From #Temp
OPEN Temp_Cursor
FETCH NEXT FROM Temp_Cursor INTO @D_D;
WHILE @@FETCH_STATUS = 0
BEGIN
Set @Str_D = @Str_D + @D_D;
Set @I_D = @I_D + 1;
If @I_D = @Num_D
break;
Set @Str_D = @Str_D + @Patten;
FETCH NEXT FROM Temp_Cursor INTO @D_D
End
Select @Str_D;
Close Temp_Cursor;
Deallocate Temp_Cursor;
Drop Table #Temp;
End
GO
--测试语句:Exec ReturnStr '|'
热心网友
时间:2024-12-13 10:04
--建表
create table tb(id int, value varchar(10))
insert into tb values(1, 'aa')
insert into tb values(1, 'bb')
insert into tb values(2, 'aaa')
insert into tb values(2, 'bbb')
insert into tb values(2, 'ccc')
go
--建函数
CREATE FUNCTION dbo.f_str(@id int)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @r varchar(8000)
SET @r = ''
SELECT @r = @r + ',' + value FROM tb WHERE id=@id
RETURN STUFF(@r, 1, 1, '')
END
GO
-- 调用函数
SELECt id, value = dbo.f_str(id) FROM tb GROUP BY id
drop table tb
drop function dbo.f_str
参照这个函数这个比你要的复杂一些
依照这个函数你就成功了
不懂可以HI我