开发者

How can I make this query to accept dynamic table names?

开发者 https://www.devze.com 2023-03-05 16:25 出处:网络
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

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) = ''
 开发者_StackOverflow中文版   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:)


You will need to use dynamic SQL.

That's the only way to parameterize table names.


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('').

declare @SQL nvarchar(max), @TableName nvarchar(max)
set @TableName='dbo.vwAsset'
set @SQL=(select 'cast(isnull('+name+','''') as nvarchar)+'' ''+'
from sys.columns where object_id=object_id(@TableName)
for XML Path('')
)

set @SQL=LEFT(@SQL,LEN(@SQL)-1)

set @SQL='select '+@SQL+' from '+@TableName

exec sp_ExecuteSQL @SQL,N''

Hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号