SQL VIEWS /数据类型转换

时间:2017-06-21 07:37:04

标签: sql-server

我正在努力创造一个观点。视图中的一个字段是smalldatetime字符类型。我试图在特定日期范围内显示记录。似乎存在字符类型转换问题。我得到的错误是"将varchar数据类型转换为smalldatetime数据类型会导致超出范围的值。"

这是我的一段代码

CREATE VIEW erep
AS
SELECT [iInvoiceID] as invoice_id
      ,[OrderDate] as rrdate
      ,[cDescription] as product
      ,[fQtyProcessed] as qty
      ,[fUnitPriceExcl] as unitpricenotax
      ,[fUnitPriceIncl] as unitpricewithtax
      ,[fUnitCost] as unitcost
      ,[fTaxRate] as taxrate
      ,[fQuantityLineTotIncl] as totalwithtax
      ,[fQuantityLineTotExcl] as totalnotax
      ,[fQuantityLineTotInclNoDisc] as totalwithtaxnodiscount
      ,[fQuantityLineTotExclNoDisc] as totalnotaxnodisc
      ,[iDeliveryStatus] as deliverystatus
        FROM _bvSalesOrdersFull
  where orderdate >= '2017-01-01 00:00:00' AND orderdate < '2017-31-12 00:00:00';

1 个答案:

答案 0 :(得分:0)

对于您的日期时间文字,无论语言/文化设置如何,都使用明确的格式:

CREATE VIEW erep
AS
SELECT [iInvoiceID] as invoice_id
      ,[OrderDate] as rrdate
      ,[cDescription] as product
      ,[fQtyProcessed] as qty
      ,[fUnitPriceExcl] as unitpricenotax
      ,[fUnitPriceIncl] as unitpricewithtax
      ,[fUnitCost] as unitcost
      ,[fTaxRate] as taxrate
      ,[fQuantityLineTotIncl] as totalwithtax
      ,[fQuantityLineTotExcl] as totalnotax
      ,[fQuantityLineTotInclNoDisc] as totalwithtaxnodiscount
      ,[fQuantityLineTotExclNoDisc] as totalnotaxnodisc
      ,[iDeliveryStatus] as deliverystatus
        FROM _bvSalesOrdersFull
  where orderdate >= '2017-01-01T00:00:00' AND orderdate < '2017-12-31T00:00:00';

但不是我希望期望结束点为'2018-01-01T00:00:00',除非您打算在 12月的最后一天内排除发生的订单。< / p>

明确的日期格式为YYYYMMDDYYYY-MM-DD'T'hh:mm:ssYYYY-MM-DD'T'hh:mm:ss.mil。其他一些格式可能这些天运作良好,但历史上SQL Server可能会与它们混淆;我相信,YYYY-MM-DD曾经有过问题。与使用空格作为日期/时间分隔符一样。