2011-05-11 94 views
0

這是我的函數,它主要將所有行數據連接成一個字符串。我知道一個名爲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 

感謝提前:)

回答

2

您將需要使用dynamic SQL

這是參數化表名稱的唯一方法。

1

這不完全是你正在尋找的東西,但它可能會指向你正確的方向。這在For XML Path('')中使用動態sql和連接技巧。

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 '[email protected]+' from '[email protected] 

exec sp_ExecuteSQL @SQL,N'' 

希望這會有所幫助!