T-SQL函数返回1个以上的值

时间:2013-11-01 12:17:52

标签: sql-server tsql sql-server-2005

我有一个T-SQL函数来返回statistics属性的所有关联列 我正在传递sys.stats系统表的stats_id和object_id。 我需要用','分隔的所有列,但我的函数只返回第一列。请帮助 我正在使用Sql server 2005

create FUNCTION fGetstatscols (
    @objectid INT,
    @stats_id  INT
)
RETURNS NVARCHAR(200)
AS
BEGIN
    DECLARE @V_IncludedCol NVARCHAR(200)
    DECLARE collist CURSOR
    ( select (name) from sys.columns where Object_id =@objectid 
        and column_id in (select column_id from  sys.stats_columns where object_id=@objectid 
        and stats_id=@stats_id))   
    OPEN collist
    FETCH NEXT FROM collist INTO @V_IncludedCol
    WHILE @@FETCH_STATUS <> 0
    begin 
        Select @V_IncludedCol = COALESCE(@V_IncludedCol + ',', '') 
    END
    close collist
    deallocate collist
    RETURN @V_IncludedCol
END

2 个答案:

答案 0 :(得分:3)

避免在此和大多数其他情况下使用光标。

CREATE FUNCTION fGetstatscols (
    @objectid INT,
    @stats_id  INT
)
RETURNS NVARCHAR(200)
AS
BEGIN
    DECLARE @V_IncludedCol NVARCHAR(200) = ''
    SELECT @V_IncludedCol += ','+name 
    FROM sys.columns c 
    WHERE Object_id =@objectid 
        and exists (SELECT 1 from  sys.stats_columns 
                    WHERE object_id=@objectid 
                     and stats_id=@stats_id
                     and c.column_id=column_id)
    RETURN stuff(@V_IncludedCol, 1,1, '')
END

你应该知道,可以让函数返回一个包含结果的表。

答案 1 :(得分:0)

每次WHILE循环时,@V_IncludedCol变量都会被新值填充,这就是为什么你只得到一个值

create FUNCTION fGetstatscols (
    @objectid INT,
    @stats_id  INT
)
RETURNS NVARCHAR(200)
AS
BEGIN
    DECLARE @V_IncludedCol NVARCHAR(200)
    DECLARE @retval NVARCHAR(200)
    DECLARE collist CURSOR
    ( select (name) from sys.columns where Object_id =@objectid 
        and column_id in (select column_id from  sys.stats_columns where object_id=@objectid 
        and stats_id=@stats_id))   
    OPEN collist
    FETCH NEXT FROM collist INTO @V_IncludedCol
    WHILE @@FETCH_STATUS <> 0
    begin 
        if @retval is null 
            select @retval = @V_IncludedCol
        else 
            Select @retval = retval + ',' + @V_IncludedCol
    END
    close collist
    deallocate collist
    RETURN @retval
END

但你最好使用 t-clausen.dk 解决方案,避免使用游标