[英]Use case with a variable to determine whether a count has to be returned or column list
I have a situation where on a dashboard, for pending approvals I am trying to show certain items as follows我有一种情况,在仪表板上,为了等待批准,我试图按如下所示显示某些项目
The [Count] shows a numeric value of items pending approval. [计数] 显示待审批项目的数值。 On click of each of these items, there is an associated table where the records are being shown.
单击这些项目中的每一个,都会有一个关联的表格,其中显示了记录。
The way of deriving these counts is very complex and I wish to avoid making duplicate queries for count for example query #1 as推导这些计数的方法非常复杂,我希望避免对计数进行重复查询,例如查询 #1 作为
SELECT COUNT(*)
FROM tableName
and then query #2 as然后查询 #2 作为
SELECT ColumnA, ColumnB, ColumnC
FROM tableName
Since these queries are being read into my C# application, until now I've been doing the following由于这些查询被读入我的 C# 应用程序,直到现在我一直在执行以下操作
var onlyCount = true;
var subQuery = onlyCount? "COUNT(*)": "ColumnA, ColumnB, ColumnC";
var query = $"SELECT {subQuery} FROM tableName";
But with an ever-growing list of columns that needs to be managed, this makes the code look ugly.但是随着需要管理的列列表不断增加,这使得代码看起来很难看。 With calculated data in the select list, Case(s), IIF(s) in the statement the above-said solution is no longer a "maintainable" solution.
根据select列表中的计算数据,Case(s), IIF(s) in the statement,上述解决方案不再是“可维护”解决方案。 With the select query is something as demonstrated below even possible?
使用 select 查询是否可能出现如下所示的情况?
DECLARE @CountOnly AS BIT = 1
SELECT
CASE
WHEN @CountOnly = 1
THEN COUNT(*)
ELSE ColumnA, ColumnB, ColumnC
END
FROM
tableName
Have any one ever faced such a scenario?有没有人遇到过这样的情况? Or if you could point me in a direction where this can be handled better?
或者,如果你能指出一个可以更好地处理这个问题的方向?
Side note: The above query is being passed into a SqlDataReader
to fetch the data and show to the end user.旁注:上面的查询被传递到
SqlDataReader
以获取数据并显示给最终用户。
You may want to use something like this:你可能想使用这样的东西:
DECLARE @CountOnly AS BIT = 1
IF (@CountOnly = 1)
BEGIN
SELECT ColumnA, ColumnB, ColumnC
FROM MyTable
ELSE
SELECT COUNT(*)
FROM MyTable
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.