开发者

Need help in generating Query

I h开发者_JAVA百科ave a doubt in generating Query.

Which is best way in these two

Eg: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'

Eg 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


    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)


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

In this way, We should first filter the values and then join between them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜