从存储过程上的字符串转换日期和/或时间时转换失败

时间:2017-05-04 21:23:28

标签: sql-server date stored-procedures

我有两个类似的存储过程,但由于某种原因,其中一个在从字符串转换为日期格式时起作用,但另一个没有:

这是不起作用的:

exec Search_PR 'US00000001','PR00000001', '01/01/0001', '01/01/0001', 'WH00000001', 'ST00000001','Requested'

代码:

Create Procedure Search_PR 
    (@usersID CHAR(10),
     @prNo VARCHAR(20), 
     @prDateFrom Date, 
     @prDateTo Date, 
     @warehouseID CHAR(10), 
     @storageID CHAR(10), 
     @status VARCHAR(20)
   )
As
Begin
    --some other codes
    Select * 
    From PurchaseReturn pr, storage s, warehouse w, Users u 
    Where pr.storageID = s.storageID 
      and s.warehouseID = w.warehouseID 
      and w.usersID = u.usersID 
      and u.usersID = @usersID 
      and ((pr.prNo like '%' + @prNo + '%') or @prNo Is Null) 
      and (pr.prDate >= @prDateFrom Or @prDateFrom Is Null) 
      and (pr.prDate <= @prDateTo Or @prDateTo Is Null) 
      and (w.warehouseID = @warehouseID or @warehouseID Is Null) 
      and (pr.storageID = @storageID or @storageID Is Null) 
      and (pr.status = @status Or @status Is Null)
End

我从上述程序中得到此错误:

  

从字符串转换日期和/或时间时转换失败。

这个程序可以解决同样的错误:

exec Search_PO 'US00000001','PO00000001','01/01/2017','01/01/0001','--Select--'

exec Search_PO 'US00000001','1','01/01/0001','01/01/0001','--Select--'

代码:

Create Procedure Search_PO
    (@usersID CHAR(10), 
     @poNo VARCHAR(20), 
     @poDate Date, 
     @poDeliveryDate Date, 
     @status VARCHAR(20)
    )
As
Begin
    --some other codes

    Select * 
    From PurchaseOrder p, Users u, Warehouse w 
    Where p.warehouseID = w.warehouseID 
      and w.usersID = u.usersID 
      and u.usersID = @usersID 
      and ((p.poNo like '%' + @poNo + '%') or @poNo Is Null) 
      and (p.poDate>=@poDate Or @poDate Is Null) 
      and (p.poDeliveryDate >= @poDeliveryDate Or @poDeliveryDate Is Null) 
      and (p.status = @status Or @status Is Null)
End

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

你的连接语法古老而可怕。

Bad habits to kick : using old-style JOINs - Aaron Bertrand

另外,在指定字符串date时,最好使用'00010101'作为'0001-01-01'。

尝试明确地将pr.prDate转换为date

create procedure Search_pr(
    @usersid char(10) 
  , @prNo varchar(20)
  , @prDateFrom date
  , @prDateTo date
  , @warehouseid char(10)
  , @storageid char(10)
  , @status varchar(20)
  ) As
begin
set nocount on;
--some other codes
select *
from PurchaseReturn pr
 , storage s
 , warehouse w
 , Users u
where pr.storageid = s.storageid
  and s.warehouseid = w.warehouseid
  and w.usersid = u.usersid
  and u.usersid = @usersid
  and ((pr.prNo like '%' + @prNo + '%') or @prNo is null)
  and (convert(date,pr.prDate) >= @prDateFrom or @prDateFrom is null)
  and (convert(date,pr.prDate) <= @prDateTo or @prDateTo is null)
  and (w.warehouseid = @warehouseid or @warehouseid is null)
  and (pr.storageid = @storageid or @storageid is null)
  and (pr.status = @status or @status is null)
end;