如何使此查询接受动态表名称?
这是我的函数,主要将所有行数据连接到一个字符串中。我知道有一个名为 Coallasce 的函数可用,但是出于好奇,我想知道如何更改此函数以动态接受表名称。目前它只从 Employee 表中读取。
ALTER FUNCTION [dbo].[ConcatStrig]
(
@TableName varchar(64),
@FieldName varchar(64)
)
RETURNS varchar(max)
AS
BEGIN
Declare @Sql as varchar(max) = ''
Set @Sql = 'Select ' + @FieldName + ' from ' + @TableName
Declare curTemp Cursor For
Select EmpName from sp_executesql(@Sql)
Declare @StrTemp as varchar(max)
Declare @String as varchar(max) = ''
Open curTemp
Fetch Next from curTemp into @StrTemp
While @@Fetch_Status = 0
Begin
Set @String = @String + ' ' + @StrTemp
Fetch Next from curTemp into @StrTemp
End
Close curTemp
Deallocate curTemp
Return @String
END
提前致谢:)
This is my function which mainly concats all the rows data into one string. I know a function named Coallasce is available, however just out of curiosity I want to know how can I change this function to accept table names dynamically. At present it only reads from Employee table.
ALTER FUNCTION [dbo].[ConcatStrig]
(
@TableName varchar(64),
@FieldName varchar(64)
)
RETURNS varchar(max)
AS
BEGIN
Declare @Sql as varchar(max) = ''
Set @Sql = 'Select ' + @FieldName + ' from ' + @TableName
Declare curTemp Cursor For
Select EmpName from sp_executesql(@Sql)
Declare @StrTemp as varchar(max)
Declare @String as varchar(max) = ''
Open curTemp
Fetch Next from curTemp into @StrTemp
While @@Fetch_Status = 0
Begin
Set @String = @String + ' ' + @StrTemp
Fetch Next from curTemp into @StrTemp
End
Close curTemp
Deallocate curTemp
Return @String
END
Thanks in advance:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将需要使用动态 SQL。
这是参数化表名的唯一方法。
You will need to use dynamic SQL.
That's the only way to parameterize table names.
这并不完全是您正在寻找的内容,但它可能会为您指明正确的方向。这使用了动态 sql 和 For XML Path('') 中的串联技巧。
希望这有帮助!
This isn't quite exactly what you're looking for, but it might point you down the right direction. This uses dynamic sql and a neat trick for concatenation in For XML Path('').
Hope this helps!