求一个循环记录输出字符串的函数.
有我两张表
表1: a1
id(identity(1,1)) name
1 a
2 b
3 c
表2: a2 ,其中aid与表1是关联的
id aid tid
1 1 1
2 1 2
3 2 1
4 2 2
5 3 1
6 1 2
求一函数 输入 tid 返回 表1中的 id,name|id,name......
如 f1(tid=1) 返回 1,a|2,b|3,c
------解决方案--------------------Create Table a1
(id Int identity(1,1),
name Varchar(100))
Insert a1 Select 'a '
Union All Select 'b '
Union All Select 'c '
Create Table a2
(id Int identity(1,1),
aid Int,
tid Int)
Insert a2 Select 1, 1
Union All Select 1, 2
Union All Select 2, 1
Union All Select 2, 2
Union All Select 3, 1
Union All Select 1, 2
GO
--創建函數
Create Function F_TEST(@tid Int)
Returns Nvarchar(1000)
As
Begin
Declare @S Nvarchar(1000)
Select @S = ' '
Select @S = @S + '| ' + Cast(a1.id As Varchar) + ', ' + a1.name From a1 Inner Join a2 On a1.id = a2. aid Where a2.tid = @tid Order By a1.id
Select @S = Stuff(@S, 1, 1, ' ')
Return @S
End
GO
--測試
Select dbo.F_TEST(1) As name
GO
--刪除測試環境
Drop Table a1, a2
Drop Function F_TEST
--結果
/*
name
1,a|2,b|3,c
*/