从字符串转换datetime时SQL Server转换失败

时间:2013-05-09 19:46:24

标签: sql-server datetime sql-server-2005

我有这个查询在表格中填写一个日期给我这个错误信息:

  

从字符串转换日期时转换失败。

下面是我的表声明和查询。我做错了什么,我该如何解决?

CREATE TABLE #inv
(
      Rep_LName NVARCHAR(50)
    , Rep_FName NVARCHAR(50)
    , Rep_ID NVARCHAR(50)
    , Rep_Email NVARCHAR(100)
    , Rep_Status NVARCHAR(50)
    , Rep_BU NVARCHAR(50)
    , Sales_Force NVARCHAR(50)
    , Territory NVARCHAR(50)
    , Sample_Eligibility NVARCHAR(50)
    , DM_Name NVARCHAR(100)
    , Phys_Inv_Date DATETIME
    , Last_Reconciled DATETIME
    , Inv_Type NVARCHAR(50)
    , Days_Since_Last_inv INT
)

我正在尝试填充游标中的Phys_Inv_Date字段,如下所示:

OPEN Inventory_info

FETCH NEXT FROM Inventory_info INTO @rep_ID, @call_date

WHILE ( @@fetch_status = 0 ) BEGIN  

        SELECT
            @ls_Sql = 'update #inv set Phys_Inv_Date = case when inventory_type = ''physical'' then '
            + @call_date
            + ' else b.inv_date end from #inv a INNER JOIN (select top 1 call_date, rep_id from inv_header where call_date < '
            + @call_date + ' and rep_id = ''' + @rep_id
            + ''') b ON a.rep_id = b.rep_id WHERE Phys_Inv_Date IS NULL'

        EXEC (@ls_Sql)

        FETCH NEXT FROM Inventory_info INTO @rep_ID, @call_date

END

CLOSE Inventory_info
DEALLOCATE Inventory_info

2 个答案:

答案 0 :(得分:4)

将SQL与参数一起使用有什么问题?这里没有明显的理由需要动态SQL,并且假设变量是正确的数据类型,那么您不需要转换任何内容:

update 
    #inv 
set 
    Phys_Inv_Date = case 
        when inventory_type = 'physical' then @call_date
        else b.inv_date end
 from 
    #inv a 
    INNER JOIN (
        select top 1 
            call_date, 
            rep_id 
        from 
            inv_header where call_date < @call_date
            and rep_id = @rep_id
    ) b
    ON a.rep_id = b.rep_id 
WHERE 
    Phys_Inv_Date IS NULL

答案 1 :(得分:0)

假设call_date中的inventory_info是日期时间列,您需要将CONVERT更改为字符串

select @ls_Sql='
  update #inv set Phys_Inv_Date = case when inventory_type = ''physical''
                                  then ''' + CONVERT(varchar,@call_date,112) + '''
                                  else b.inv_date end
  from #inv a
  JOIN (select top 1 call_date, rep_id
        from inv_header
        where call_date < ''' + CONVERT(varchar,@call_date,112) + '''
        and rep_id = ''' + rtrim(@rep_id) + ''') b
    ON a.rep_id = b.rep_id
  WHERE Phys_Inv_Date IS NULL';

它为您提供了一个格式为YYYYMMDD的字符串,但您仍然需要将其括在引号中,这与您对@rep_id的操作非常相似。但是,我猜测@rep_id实际上是 int ,因此您可以使用RTRIM将其转换为varchar。

另请注意,SQL Server中允许 多行字符串 ,使您的代码更具可读性。