sql if,case when,stuff 使用

博客给出一段SQL代码,用于根据店铺ID和关键词查询商品信息。代码根据basicset表的查询结果分两种情况执行不同的查询逻辑,还展示了使用SqlCommand和SqlParameter执行SQL语句的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

string strSql = @"if exists(select * from basicset where shopid=@shopid and usesubtype=1) 
begin
    select distinct a.item_no 商品编号,a.item_subno 商品自编码,a.item_name 商品名称,a.item_price 价格,a.item_spec 规格, a.unit_id 多规格编号,
stuff((select ','+branch_no from t_branch_info where  shopid=a.shopid and stop_flag ='1' and 
branch_no not in(select branch_no from t_branch_item where  shopid=a.shopid and productid =a.Id) for xml path('')), 1, 1, '') as 售卖门店
,stuff((select ','+branch_no from t_branch_item where  shopid=a.shopid and productid =a.Id for xml path('')), 1, 1, '') as 未售卖门店 
,case when c.type_name is null then b.type_name else c.type_name+'--'+b.type_name end 类别
from t_item_info a 
left join t_item_type b on b.shopid=a.shopid and b.type_no = a.type_no and b.useflag ='1'
left join t_item_type c on c.shopid=a.shopid and c.parentno = a.type_no and c.useflag ='1'
where a.shopid=@shopid and  a.useflag ='1' and a.item_name like @keyword
end
else
begin
   select distinct a.item_no 商品编号,a.item_subno 商品自编码,a.item_name 商品名称,a.item_price 价格,a.item_spec 规格,a.unit_id 多规格编号,
stuff((select ','+branch_no from t_branch_info where  shopid=a.shopid and stop_flag ='1' and 
branch_no not in(select branch_no from t_branch_item where  shopid=a.shopid and productid =a.Id) for xml path('')), 1, 1, '') as 售卖门店
,stuff((select ','+branch_no from t_branch_item where  shopid=a.shopid and productid =a.Id for xml path('')), 1, 1, '') as 未售卖门店 
,b.type_name 类别
from t_item_info a 
left join t_item_type b on b.shopid=a.shopid and b.type_no = a.type_no and b.useflag ='1'
where a.shopid=@shopid and  a.useflag ='1' and a.item_name like @keyword
end";
                    SqlCommand sqlCmd = new SqlCommand(strSql, connection);
                    var parameter = new SqlParameter[]{
                        new SqlParameter("@shopid",shopid),
                        new SqlParameter("@keyword","%"+keyword+"%")
                    };

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_41469374

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值