早上好。我是SQL的初学者。
我想修改下面的MS-SQL
过程。
我想在查询语句的中间添加一个分支语句,但这并不如我所想。
谢谢!
WITH W_TEST AS (
SELECT T1.ID
,T2.NAME
,T1.ADDRESS
,T1.NUMBER
FROM TEST_TBL1 T1
INNER JOIN TEST_TBL2 T2 ON T1.OBJECTID = T2.OBJECTID
WHERE T1.TYPE != 14
-- ======= This is the part you want to modify.
IF (Condition 1)
BEGIN
GROUP BY T1.ID
,T2.NAME
,T1.ADDRESS
,T1.NUMBER
HAVING (
(SELECT MAX(NEXT_NUM) AS NEXT_NUMBER
FROM NUMBER_TBL1
WHERE GRADE = 3
) < MAX(T1.NUMBER)
)
END
ELSE
BEGIN
-- Branch statement not including grammar
END
-- ======= This is the part you want to modify.
)
答案 0 :(得分:0)
您需要创建两个单独的语句或使用动态T-SQL。既然您是新手,那么使用单独的语句将很容易使用:
IF (Condition 1)
BEGIN
WITH W_TEST AS (
SELECT T1.ID
,T2.NAME
,T1.ADDRESS
,T1.NUMBER
FROM TEST_TBL1 T1
INNER JOIN TEST_TBL2 T2 ON T1.OBJECTID = T2.OBJECTID
WHERE T1.TYPE != 14
GROUP BY T1.ID
,T2.NAME
,T1.ADDRESS
,T1.NUMBER
HAVING (
(SELECT MAX(NEXT_NUM) AS NEXT_NUMBER
FROM NUMBER_TBL1
WHERE GRADE = 3
) < MAX(T1.NUMBER)
)
...
END
ELSE
BEGIN
WITH W_TEST AS (
SELECT T1.ID
,T2.NAME
,T1.ADDRESS
,T1.NUMBER
FROM TEST_TBL1 T1
INNER JOIN TEST_TBL2 T2 ON T1.OBJECTID = T2.OBJECTID
WHERE T1.TYPE != 14
)
..
END
答案 1 :(得分:0)
首先,您需要准备所需的中间查询,然后通过与中间查询连接来构建最终查询。您可以从此链接中获得一些想法: Building Dynamic Query