1

我有这个查询来填写一个给我这个错误消息的表中的日期:

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

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

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
4

2 回答 2

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
于 2013-05-09T20:01:49.080 回答
0

假设call_dateininventory_info是一个日期时间列,您需要将其转换为字符串

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 中允许使用多行字符串,这使您的代码更具可读性。

于 2013-05-09T19:52:41.527 回答