只想显示包含值的列

时间:2016-04-18 14:11:32

标签: sql sql-server stored-procedures

我正在尝试显示当时具有值的列,但代码会显示每一列。忽略if语句不知道自己做错了什么。 Person_Permission和Person有两个表。我在Person_Permission中选择了具有值的所有列,在获取这些列名后,我使用这些列从Person表中进行选择。

USE [exampleProject]
GO
/****** Object:  StoredProcedure [dbo].[list_col_notNull]    Script Date: 2016/04/18 11:53:51 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[list_col_notNull](@username VARCHAR(20))
AS

    DECLARE @col VARCHAR(255), @cmd VARCHAR(MAX)

    SELECT * INTO #table FROM Person_Permissions
    WHERE userName = @username

    DECLARE getinfo CURSOR FOR
    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'Person_Permissions'

    SET @cmd = 'SELECT '

    OPEN getinfo

    FETCH NEXT FROM getinfo into @col

    WHILE @@FETCH_STATUS = 0
    BEGIN

        IF EXISTS(SELECT TOP 1 * FROM #table WHERE @col IS NOT NULL)
        BEGIN
            SET @cmd = @cmd + RTRIM(@col) + ','
        END
        FETCH NEXT FROM getinfo into @col
    END

    CLOSE getinfo
    DEALLOCATE getinfo
    SET @cmd = LEFT(@cmd, LEN(@cmd) -1) + ' FROM [Person]'
    select * from #table
    EXEC(@cmd)
    SELECT(@cmd)

1 个答案:

答案 0 :(得分:0)

下面是一个示例,它通过检查while语句中列中所有值的长度来完成您正在寻找的内容,因此这应该比游标更有效。

void onButtonTap (id sender)
        {
            UIButton button = (UIButton)sender;

        this.sectionHeaderViewDelegate.buttonTapped (this.section);

        }