2017-01-16 71 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子句将导致当有与该类别标识您正在搜索中没有商品它只返回结果。