0

使用 SQL 2008,我有以下代码:

    if (exists (select * from tempdb.INFORMATION_SCHEMA.TABLES where TABLE_NAME = '##tempz'))
begin
drop table ##tempz
end
else
DECLARE @startDate datetime, @enddate datetime, @storename varchar(20), @showstore int, @showcashier int, @showregister int, @showdate int
SET @startDate = '1/1/2011'
SET @enddate = '1/1/2013'
SET @storename = '01'
SET @showstore = 1
SET @showcashier = 1
SET @showregister = 1
SET @showdate = 1

DECLARE @cols AS NVARCHAR(MAX),@colsNull AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(c.CurrencyDesc)
FROM rpPay p LEFT JOIN RPTrs r ON p.ReceiptNo = r.ReceiptNo LEFT JOIN Currencies c ON c.POSCurrency = LEFT(p.paytype,1)
WHERE r.trsdate >= @startDate AND r.trsdate <= @enddate
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')

SELECT @colsNull = STUFF((SELECT DISTINCT ', IsNull(' + QUOTENAME(c.CurrencyDesc) +', 0) as '+ QUOTENAME(c.CurrencyDesc)
FROM rpPay p LEFT JOIN RPTrs r ON p.ReceiptNo = r.ReceiptNo LEFT JOIN Currencies c ON LEFT(p.paytype,1) = c.POSCurrency
WHERE r.trsdate >= @startDate AND r.trsdate <= @enddate
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'),1,1,'')

SET @query = 'select date, cashregister, storeid, cashier, '+@colsNull+' into ##tempz
FROM
(SELECT cast(r.trsdate AS DATE) date,c.CurrencyDesc,p.amount,r.cashregister,r.storeid,r.cashier
FROM rpPay p LEFT JOIN RPTrs r ON p.ReceiptNo = r.receiptno LEFT JOIN Currencies c ON LEFT(p.paytype,1) = c.POSCurrency
WHERE r.trsdate >= '''+ convert(varchar(10), @startDate, 101) +''' AND r.trsdate <= '''+ convert(varchar(10), @endDate, 101) +''' 
) p
pivot
(sum(amount) FOR CurrencyDesc in('+@cols+')) piv'
execute(@query)

select * from ##tempz

这返回 返回

我想要的是,如果其中任何一个:

SET @showstore = 1
SET @showcashier = 1
SET @showregister = 1
SET @showdate = 1

是 0,那么我不想在结果窗口中显示它。所以如果@showcashier 为0,那么Cashier 将不会显示

4

2 回答 2

2

你不能,使用常规 SQL。SQL 语句返回的列已定义。

你有三个选择。首先是在应用程序级别选择列。第二个是返回 NULL 值(如果语法正确,您的查询将执行此操作。第三个是使用“动态”sql。即,将 SQL 查询生成为字符串,然后执行它。

第三个选项取决于您使用的数据库。

于 2013-02-04T21:08:45.857 回答
1

这样做的一种方法是使用这样的存储过程:

CREATE PROCEDURE GetData
    @show tinyint
AS
BEGIN
    IF @show = 1
    BEGIN
        select CurrencyDesc, POSCurrency from Currencies;
    END
    ELSE
        select CurrencyDesc from Currencies;
END 

而不是像这样执行它:

exec GetData 1 -- returns 2 columns

exec GetData 0 -- returns one column
于 2013-02-04T21:27:38.330 回答