2017-01-16 72 views
0

我已經SP ..在此我嘗試當descitem值有「 - 」,然後希望得到價值@Typeid 在這個參數我嘗試這個描述,而不是「 - 」

什麼以前修改

ALTER PROCEDURE dbo.GetItem 
    @Typeid Smallint 
As 
    begin 
     select 0 Itemid, '-' descitem 
     union all 
     select ci.Itemid, ci.descitem descitem 
     from Item ci where [email protected] 
    END 
return 

當我執行這說明導致這樣

exec GetItem 38 

    Itemid descitem 
     0  - 

,如果我用另一種嘗試像

exec GetItem 39 
Itemid descitem 
    0  - 
    83  issues 
    84  system 
    85  repair 

後修改

ALTER PROCEDURE dbo.GetItem 
    @Typeid Smallint 
As 
begin 
    declare @descitem nvarchar(50) 
     select 0 Itemid, '-' descitem 
     union all 
     select ci.Itemid, ci.descitem descitem 
     from Item ci where [email protected] 
     if @descitem='-' 
    begin 
     select Typeid, descitem descitem from Type 
    end 
    END 
return 

,所以我想,當我執行

exec GetItem 38 

則希望得到38說明,而不是 「 - 」

UPDATE

tables 

    **type table** 
typeid descitem  catg_id 
1  fruits  4 
2  suggestions 5 
3  reports  6 

**item table** 

itemid descitem catg_id typeid 
1  good  5   2 
2  bad   5   2 
3  average  5   2 
4  report1  6   3 
5  report2  6   3  

這樣提到,沒有4 catg_id在項目表 所以想有水果的typeid然後希望結果 也顯示當我執行的GetItem 4

item descitem 
0  fruits 
+0

請編輯您的問題,包括相關的表格DDL,一些樣本數據作爲DML和期望的結果。 –

+0

@Zohar最後請檢查更新 –

+0

@cooluser,你是用'catg_id'還是'typeid'搜索?你的代碼使用@typeid,你的描述性例子是關於'catg_id = 4'的過濾。 –

回答

0

這不是很清楚如果您正在按類別id(按照文本中的建議)或按類型if(按照查詢中的建議)搜索項目。

我與類別ID去從文本提示:

ALTER PROCEDURE dbo.GetItem 
    @CategoryId Smallint 
As 
BEGIN 

    SELECT Itemid, descitem descitem 
    FROM Item 
    WHERE catg_id = @CategoryId 

    UNION ALL 

    SELECT 0, descitem 
    FROM type 
    WHERE catg_id = @CategoryId 
    AND NOT EXISTS 
    (
     SELECT 1 
     FROM Item 
     WHERE catg_id = @CategoryId 
    ) 

END 

的,其中第二查詢的WHERE子句將導致當有與該類別標識您正在搜索中沒有商品它只返回結果。