我如何归档以下内容?
如果@chk = 0,则在结果中包括第4列,否则仅保留3列, 如果选择了第4列,则该第4列需要左连接, 并在分组依据中包括第4列
DECLARE @chk AS INT= 0;
SELECT a.Ledgerid,
b.LedgerCity,
CASE WHEN @chk = 0 THEN SUM(a.TotalAmount) ELSE SUM(a.NetAmount) END,
CASE WHEN @chk = 0 THEN c.ledgername END (is it possilbe to completly do not have this column if @chk <> 0)
FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID
LEFT JOIN LedgerMaster AS C ON A.LedgerID = C.LedgerID --This left join is required only if @chk=0, same logic is there in above select statement
GROUP BY A.LedgerID,
B.LedgerCity;
C.LedgerName; -- this 3rd group required only if @chk=0
一些帖子建议在分组依据中如何使用案例。我尝试了“ @ chk = 0时的情况,然后a.Ledgerid,b.Ledgercity,c.LedgerName否则a.Ledgerid,b.Ledgercity END进行分组;但这不起作用
答案 0 :(得分:0)
使用IF .. ELSE块
IF @chk = 0
BEGIN
SELECT a.Ledgerid,
b.LedgerCity,
CASE WHEN @chk = 0 THEN SUM(a.TotalAmount) ELSE SUM(a.NetAmount) END,
CASE WHEN @chk = 0 THEN c.ledgername END
FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID
LEFT JOIN LedgerMaster AS C ON A.LedgerID = C.LedgerID --This left join is required only if @chk=0, same logic is there in above select statement
GROUP BY A.LedgerID, B.LedgerCity, C.LedgerName;
END
ELSE
BEGIN
SELECT a.Ledgerid,
b.LedgerCity,
CASE WHEN @chk = 0 THEN SUM(a.TotalAmount) ELSE SUM(a.NetAmount) END
FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID
GROUP BY A.LedgerID, B.LedgerCity;
END
答案 1 :(得分:0)
如果确定,数据库外部的任何人都无法运行查询并执行sql注入,只需使用简单的dynamic-sql语句
DECLARE @sql AS NVARCHAR(MAX);
DECLARE @chk AS INT= 0;
set @sql = N'SELECT a.Ledgerid,
b.LedgerCity, ' +
CASE WHEN @chk = 0 THEN 'SUM(a.TotalAmount) ' ELSE 'SUM(a.NetAmount) ' END +
CASE WHEN @chk = 0 THEN ', c.ledgername ' ELSE ' ' END +
'FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID ' +
CASE WHEN @chk=0 THEN 'LEFT JOIN LedgerMaster AS C ON A.LedgerID = C.LedgerID ' ELSE '' END +
'GROUP BY A.LedgerID,
B.LedgerCity' +
CASE WHEN @chk = 0 THEN ', C.LedgerName;' ELSE ';' END;
exec sp_executesql @sql