存储过程传递像语句以防万一

时间:2016-04-01 06:57:13

标签: sql sql-server

ALTER PROCEDURE [dbo].[ViewSo]
    @Dt1 as datetime,
    @Dt2 as datetime,
    @CusName as nvarchar,
    @so_no as nvarchar
AS
BEGIN
    SET NOCOUNT ON;

    SELECT * 
    FROM
        (SELECT 
             0 as stat,
             m.id, f.id as fg_id, f.fg_des, m.so_no,
             Replace(CONVERT(NVARCHAR, CAST(m.so_date AS DATE) , 106),' ','-') AS so_date,
             Convert(NVARCHAR,CAST(m.so_date AS DATE),101) AS so_date1,
             m.cus_name, m.so_cus_id, m.doc_no, m.sale_person, m.so_rem,
             f.fg_des AS eXP1, f.fg_qty,
             CONVERT(VARCHAR(10), CAST(f.req_date AS DATE), 101) AS req_date,
             CASE 
                WHEN COALESCE (q.tot_req_qty, 0) < f.fg_qty 
                   THEN 'Not Updated' 
                   ELSE 'Updated' 
             END AS req_qty_stat,
             'SO No :' + CONVERT(varchar(15), m.so_no) + '/SO Date :' + CONVERT(varchar(15), REPLACE(CONVERT(NVARCHAR, CAST(m.so_date AS DATE), 106), ' ', '-')) + '/Cus Name :' + CONVERT(varchar(15), m.cus_name) + '/Sales Prsn :' + CONVERT(varchar(15), m.sale_person)  AS filter ,
             f.fg_no,m.so_stat,
             m.del_flag, m.st_stat, m.st_rem    
         FROM   
             so_mas AS m 
         INNER JOIN   
             so_fg AS f ON m.id = f.so_id 
         LEFT OUTER JOIN    
             (SELECT        
                  fg_id, SUM(req_qty) AS tot_req_qty     
              FROM   
                  fg_qty
              WHERE        
                  (del_flag = 0)    
              GROUP BY fg_id) AS q ON q.fg_id = f.id  
         WHERE
             m.del_flag = 0) AS S 
    WHERE
        CONVERT(datetime, s.so_date) BETWEEN @Dt1 AND @Dt2  
        AND S.cus_name LIKE 
                  CASE WHEN @CusName = '' THEN S.cus_name 
                       ELSE +'%' + @CusName + '%'  
                  END
    ORDER BY 
        s.so_date;
END

这是我的存储过程传递like语句以防万一。如果作为查询运行它可以正常工作。如果我用作存储的产品导致错误的结果。

请帮我解决。

1 个答案:

答案 0 :(得分:0)

替换WHERE

的这一部分
AND S.cus_name LIKE 
              CASE WHEN @CusName = '' THEN S.cus_name 
                   ELSE +'%' + @CusName + '%'  
              END

使用

AND S.cus_name LIKE 
              CASE WHEN @CusName = '' THEN S.cus_name 
                   ELSE '%' + @CusName + '%'  
              END