2017-09-07 51 views
0

我想在SELECT查詢中使用IF語句。這是這個例子。 我有3個表,它保持客戶信息,模型信息和股票。我想爲每個客戶提供最適合的模型。所以在我第一次嘗試,如果客戶收入低於5000我想提供便宜的模型,存在於該商店,否則該商店的任何模型。 但我不能在SELECT WHERE部分使用IF clouse。選擇查詢中的IF子句用法SQL Server

SELECT TOP 1 @vmodel = stocks.model , @vsloc = stocks.sloc , @vyear = models.year , @vcost = models.cost <br>FROM bistore.dbo.stocks 
JOIN bistore.dbo.models 
ON stocks.model = models.model 
WHERE stocks.sloc<>'Main' 
AND stocks.stock > 0 
AND models.mat IN (
IF (@vincome<5000) SELECT DISTINCT mat from models where mat<>'Carbon' 
ELSE SELECT DISTINCT mat from models 
) /* If income is less than 5000 than chose cheap models , else whatever) */ 

**更新**
當客戶登錄到我的門,我想給他/她最好的模型適合他。我會檢查他的收入,在他附近存放股票並以橫幅提供給他。這是我的表格樣本。

CustomerInfo

ModelInfo

DECLARE @vcname VARCHAR(50)
DECLARE @vckids INT
DECLARE @vcleng INT
DECLARE @vcweig INT
DECLARE @vcincome INT
DECLARE @vyear INT
DECLARE @vcost INT

SELECT TOP 1 @vcname = nmsnm,@vckids =孩子,@vcleng =一愣,@vcweig = weig,@vcincome =來自客戶的訂單收入ID DESC


DECLARE @vmodel VARCHAR(50)
DECLARE @vsloc VARCHAR(50)
SELECT TOP 1 @vmodel = stocks.model,@vsloc = stocks.sloc,@vyear = models.year,@vcost = models.cost FROM bistore .dbo.stocks
JOIN bistore.dbo.models
ON stocks.model = model s.model
WHERE stocks.sloc <> '主'

AND stocks.stock> 0
AND models.mat IN(
IF(@vincome < 5000)BEGIN從模型SELECT DISTINCT墊,其中墊<> '碳' END
ELSE BEGIN SELECT DISTINCT墊從模型END
)/ *如果收入低於5000比選擇便宜的車型,否則無論)/
和models.frames IN(選擇模式,使框架<幀48)/
選擇適合長度的模型/
和models.type <> '兒童自行車'/
如果有孩子,不管選擇了(不是更大然後長)*/
ORDER BY NEWID()

+0

你能給我們一些樣本數據和預期結果嗎 – GuidoG

回答

0

在MySQL它的CASE語句其中的細節是here

一個可能的使用(請參閱您的正確的語法對象):

SELECT TOP 1 @vmodel = stocks.model , @vsloc = stocks.sloc , @vyear = models.year , @vcost = models.cost <br>FROM bistore.dbo.stocks 
JOIN bistore.dbo.models 
ON stocks.model = models.model 
WHERE stocks.sloc<>'Main' 
AND stocks.stock > 0 
AND models.mat IN (
    CASE sign(@vincome - 5000) 
     WHEN -1 then (SELECT DISTINCT mat from models where mat<>'Carbon') 
     ELSE '(SELECT DISTINCT mat from models) 
    END 
    ) /* If income is less than 5000 than chose cheap models , else whatever) */ 

PS:註冊是一招我用它來模仿大於/等於/小控制CASE語法的更好的理解。

1

你不需要IFCASE,只是一個額外的AND和反向@vincome檢查:

SELECT TOP 1 
     @vmodel = stocks.model , 
     @vsloc = stocks.sloc , 
     @vyear = models.year , 
     @vcost = models.cost <br> 
FROM bistore.dbo.stocks 
JOIN bistore.dbo.models 
ON  stocks.model = models.model 
WHERE stocks.sloc <>'Main' 
AND stocks.stock > 0 
AND (@vincome >= 5000 OR models.mat <> 'Carbon') 

你看,你甚至不需要一個子查詢。