不知道如何在查询的select子句中使用varchar变量

时间:2019-08-01 19:41:38

标签: sql-server tsql variables varchar

我正在尝试在自己的选择中使用varchar变量,但该变量将注册为字符串并仅输出字符串本身,而不是将其视为实际列。

在线解决方案不是很多,因为这似乎不是很多人遇到的问题。

Declare @counter INT = 0
Declare @totalcol INT
Declare @col VARCHAR(50)


select @totalcol = count(*)
FROM [Loyalty_DW].information_schema.columns
WHERE table_name = 'Transactions'


while (@counter < @totalcol)
    begin
        select @col = COLUMN_NAME   
        from [Loyalty_DW].information_schema.columns
        where table_name = 'Transactions'
        order by (select null)
        offset @counter rows
        fetch next 1 rows only

        select distinct(@col)
        from [Loyalty_DW].dbo.Transactions

        set @counter += 1
    end

输出只是一个字符串,没有返回实际数据。就像我要说的那样,从表名中选择'asdf'一样……它将只输出'asdf'。

1 个答案:

答案 0 :(得分:1)

您可以使用CURSOR语句而不是WHILE语句,因为戈登说您需要使用动态SQL:

DECLARE  @columName AS NVARCHAR(50);
DECLARE  @sqlText AS NVARCHAR(1000);

DECLARE cursor_name CURSOR FOR
SELECT COLUMN_NAME
FROM [Loyalty_DW].INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Transactions'
ORDER BY(SELECT NULL)

OPEN cursor_name  
FETCH NEXT FROM cursor_name INTO @columName

WHILE @@FETCH_STATUS = 0  
BEGIN 

    SET @sqlText = N'SELECT DISTINCT ' +  @columName + ' FROM [Loyalty_DW].dbo.Transactions'
    EXEC (@sqlText)

    FETCH NEXT FROM cursor_name INTO @columName 
END

CLOSE cursor_name
DEALLOCATE cursor_name