SQL Server条件顺序依据

前端之家收集整理的这篇文章主要介绍了SQL Server条件顺序依据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在sql Server 2005中有一个SQL查询,当我包含条件顺序时,它会中断.当我删除订单时,查询有效.当我通过条件明确地写出订单时(例如,通过p.Description订购),它可以工作.当我包含条件顺序时,我得到错误,
  1. 'Conversion Failed when converting character string to smalldatetime data type'

sql Server没有向我显示哪行代码导致此错误.我想知道如何解决这个问题,以便我可以使用条件顺序或解决哪一列在转换中失败.

  1. declare @SearchTerm nvarchar(255)
  2. declare @SortBy nvarchar(255)
  3. declare @Months int
  4. declare @VendorID int
  5. declare @ProductID int
  6.  
  7. set @SearchTerm = 'focus'
  8. set @SortBy = 'product'
  9. set @Months = 3
  10. set @VendorID = null
  11. set @ProductID = null
  12.  
  13. -- This makes it so the @Month will filter by n number of months ago.
  14. declare @PrevIoUsMonths datetime
  15. if @Months is null
  16. begin
  17. set @PrevIoUsMonths = 24
  18. end
  19. else
  20. begin
  21. set @PrevIoUsMonths = DateAdd(month,-@Months,GetDate())
  22. end
  23.  
  24. select
  25. a.dsAlertID as AlertID,a.ProductID,v.VendorID,p.Description as ProductName,v.LongName as VendorName,a.Introduction,a.Writeup,a.DateAdded
  26. from
  27. ev_ds_Alerts a
  28. left outer join
  29. tblProducts p on a.ProductID = p.ProductID
  30. left outer join
  31. tblVendors v on v.VendorID = p.VendorID
  32. where
  33. ( @SearchTerm is null or ( a.Writeup like '% ' + @SearchTerm + '%' or a.Introduction like '% ' + @SearchTerm + '%') )
  34. and (( @Months is null ) or ( @Months is not null and a.DateAdded >= @PrevIoUsMonths))
  35. and (( @VendorID is null ) or ( @VendorID is not null and v.VendorID = @VendorID ))
  36. and (( @ProductID is null ) or ( @ProductID is not null and p.ProductID = @ProductID ))
  37. order by
  38. case @SortBy
  39. when 'product' then p.Description
  40. when 'vendor' then v.LongName
  41. else a.DateAdded
  42. end
  43.  
  44. -- order by p.Description or v.LongName works when explicitly writing them out!

解决方法

根据上一个答案,尝试:

订购
案例@SortBy
当’产品’然后p.Description
当’供应商’然后v.LongName
否则转换(VARCHAR(25),a.DateAdded,20)

这应该给你你想要的排序,因为它将格式化日期字符串yyyy-mm-dd hh:mm:ss.

猜你在找的MsSQL相关文章