我对生成查询有疑问。
这两个中最好的方式
例如:1
DECLARE @SQLQuery varchar(MAX)
SET @SQLQuery='Select tab1.Name,tab2.Name From table1 INNER JOIN table2 ON table2.ID=table1.ID'
IF @Val=0
SET @SQLQuery=@SQLQuery+' where table1.ID>5'
ELSE
SET @SQLQuery=@SQLQuery+' where table2.ID>5'
例如2:
IF @Val=0
BEGIN
Select tab1.Name,tab2.Name
From table1
INNER JOIN table2
ON table2.ID=table1.ID
WHERE table1.ID>5
END
ELSE
BEGIN
Select tab1.Name,tab2.Name
From table1
INNER JOIN table2
ON table2.ID=table1.ID
WHERE table2.ID>5
END
答案 0 :(得分:1)
Select tab1.Name,tab2.Name
From table1
INNER JOIN table2
ON table2.ID=table1.ID
WHERE (@Val=0 AND table1.ID>5) OR (@Val!=0 AND table2.ID>5)
答案 1 :(得分:0)
IF @Val = 0
BEGIN
Select T1.Name From
(
Select Name From table1 Where Id > 5
)T1
INNER JOIN table2 T2 ON T2.ID = T1.ID
END
ELSE
BEGIN
Select T2.Name From
(
Select Name From table2 Where Id > 5
)T2
INNER JOIN table1 T1 ON T1.ID = T2.ID
END
通过这种方式,我们应该首先过滤值,然后在它们之间加入。