说我有以下示例字符串:
SELECT a, b, c FROM table1 ORDER BY c
我如何(通过字符串操作)将SELECT a, b, c
更改为SELECT COUNT(a)
并删除ORDER BY
子句?
我需要在我的代码中生成一个生成的查询并对其进行修改,以便我可以运行查询的COUNT()
版本,并显示一个标签,其中包含标记为打印总数的记录数。
修改
假设我有一个更复杂的查询,我正在执行联合。为了获得与上面提到的相同的功能,我需要做什么?我只是将我的第一个SELECT
条款更改为COUNT(*)
或......?
SELECT a.memno,
a.name,
a.addr1,
a.addr2,
a.city,
a.state,
a.zip,
a.sex,
a.lname,
a.ssan,
b.addr1 as old_addr1,
b.addr2 as old_addr2,
b.city as old_city,
b.state as old_state,
b.zip as old_zip,
b.timec
FROM library1.table1 a, library1.table2 b
WHERE a.memno = b.memno and
b.groupid = 'P2' and
b.type = 'B' and
b.datec = 20131206 AND
(a.addr1 <> b.addr1 or a.addr2 <> b.addr2 or a.city <> b.city or a. state <> b.state or a.zip <> b.zip)
UNION
SELECT
a.memno,
a.name,
a.addr1,
a.addr2,
a.city,
a.state,
a.zip,
a.sex,
a.lname,
a.ssan,
b.addr1 as old_addr1,
b.addr2 as old_addr2,
b.city as old_city,
b.state as old_state,
b.zip as old_zip,
b.timec
FROM library2.table1 a, library2.table2 b
WHERE a.memno = b.memno and
b.groupid = 'N2' and
b.type = 'B' and
b.datec = 20131206 AND
(a.addr1 <> b.addr1 or a.addr2 <> b.addr2 or a.city <> b.city or a. state <> b.state or a.zip <> b.zip) ORDER BY timec desc
答案 0 :(得分:1)
如果字符串真的一致,一种方法是:
var input = "SELECT a, b, c FROM table1 ORDER BY c";
var output = input.Replace(
input.Substring(0, input.IndexOf("FROM") - 1),
"SELECT COUNT(*)");
var orderByIndex = output.IndexOf("ORDER BY");
var output = output.Replace(
output.Substring(orderByIndex, output.Length - orderByIndex),
"");
我知道我在使用SELECT COUNT(*)
,但这是为了保持算法简单。如果您通过其他方式可以随时获得关键字段,请将其插入,但我会说如果您必须将其从字符串中删除,则解析的复杂性不值得分解。
答案 1 :(得分:0)
一种可能的解决方案是将整个查询放入子查询中进行计数(假设您不关心ORDER子句):
SELECT COUNT(1) FROM (
SELECT a, b, c FROM table1 ORDER BY c
)