仅在结果的一列上应用

时间:2018-10-03 07:39:02

标签: sql sql-server

这是示例模板

UserDetails : id,UserName,IsShow
Brand       : id,BrandName
Product     : id,ProductName
BrandProduct:id,brandid,productid,price

如果Isshow为假,则显示整个价格,否则隐藏第二至第四位数字(价格为5位数字)

查询:

create procedure Sp_Details
@brandid int,
@productid int,
@IsShow bit
as
begin
        select B.Brandname,P.Producetname,Bp.Price
        from BrandProduct Bp
        inner join B
        on Bp.brandid = B.id
        inner join P
        on Bp.productid = P.id
        where brandid = @brandid
        and productid = @productid 
end

我不想使用case,isnull或任何用户创建的函数,因为它可以逐行工作。在这里,@ Isshow是false还是true,并非特定于每条记录,对于所有记录都是相同的。

除动态sql之外,还是用其他方法两次编写相同的查询。是否还有其他方法可以实现不必两次编写相同查询的地方?因为一些查询的大小更大。

If(@Isshow = false)
begin
     select B.Brandname,P.Producetname,Bp.Price
        from BrandProduct Bp
        inner join B
        on Bp.brandid = B.id
        inner join P
        on Bp.productid = P.id
        where brandid = @brandid
        and productid = @productid 
end
else
begin
      select B.Brandname,P.Producetname, REPLACE(Price, (SUBSTRING(Price,2, 3)), 'xxx')
        from BrandProduct Bp
        inner join B
        on Bp.brandid = B.id
        inner join P
        on Bp.productid = P.id
        where brandid = @brandid
        and productid = @productid 
end

3 个答案:

答案 0 :(得分:0)

select
    B.Brandname,
    P.Producetname,
    REPLACE(Price, (SUBSTRING(Price,2, 3*@Isshow)), 'xxx')
from
    BrandProduct Bp
    inner join B on Bp.brandid = B.id
    inner join P on Bp.productid = P.id
where
    brandid = @brandid
    and productid = @productid 

答案 1 :(得分:0)

我通常使用CASE WHEN语句执行此操作

SELECT B.Brandname,
       P.Producetname,
       CASE
            WHEN @Isshow = 0 THEN CAST(Bp.Price AS VARCHAR(MAX))
            WHEN @Isshow = 1 THEN REPLACE(Bp.Price, (SUBSTRING(Bp.Price,2, 3)), 'xxx')
       END AS [Price]
FROM BrandProduct Bp
INNER JOIN B
ON Bp.brandid = B.id
INNER JOIN P
ON Bp.productid = P.id
WHERE brandid = @brandid
AND productid = @productid 

答案 2 :(得分:0)

正如@Squirrel所建议的,这应该在您的表示层/前端应用程序中处理。


此外,您可以使用replacesubstring表达式中实现此功能,而不必使用stuff case

declare @price int = 12345;
declare @show bit = 0;

select @price as Show
      ,stuff(@price,2,3,'xxx') as NoShow

      ,case when @show = 1
            then cast(@price as varchar(5))
            else stuff(@price,2,3,'xxx')
            end as ConditionalShow
;

输出:

+---------+----------+-------------------+
|  Show   |  NoShow  |  ConditionalShow  |
+---------+----------+-------------------+
|  12345  |  1xxx5   |  1xxx5            |
+---------+----------+-------------------+

工作示例:http://rextester.com/ASPBV49833