描述而不是" - "

时间:2017-01-16 06:11:46

标签: sql-server procedure

我有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 ci.Typeid=@Typeid 
    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 ci.Typeid=@Typeid 
        if @descitem='-'
    begin
        select Typeid, descitem descitem from Type
    end
    END
return

所以当我执行时我想要

 exec GetItem 38

然后想要获得38而不是" - "

的描述

更新

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

1 个答案:

答案 0 :(得分: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子句将导致它仅在没有您正在搜索的类别ID的项目时返回结果。