0

我有一个 T-SQL 函数来返回统计属性的所有关联列,我正在传递 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
4

2 回答 2

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

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

于 2013-11-01T12:42:40.160 回答
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解决方案,避免使用游标

于 2013-11-01T12:44:45.187 回答