update  a  set endtime = dateadd(b.unit,b.aging,a.createtime) 
from 表A a ,表B b where a.type  =b.type  
没试,不知道这样行不。
不行就定义一个字符串,然后exec(字符串)

解决方案 »

  1.   

    ----------------------------------------------------------------
    -- Author  :DBA_Huangzj(發糞塗牆)
    -- Date    :2014-01-06 16:06:13
    -- Version:
    --      Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) 
    -- Dec 28 2012 20:23:12 
    -- Copyright (c) Microsoft Corporation
    -- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
    --
    ----------------------------------------------------------------
    --> 测试数据:[A]
    if object_id('[A]') is not null drop table [A]
    go 
    create table [A]([id] varchar(3),[type] varchar(1),[createtime] datetime,[endtime] sql_variant)
    insert [A]
    select '001','A','2013-10-1',null
    --> 测试数据:[B]
    if object_id('[B]') is not null drop table [B]
    go 
    create table [B]([id] int,[type] varchar(1),[aging] int,[unit] varchar(2))
    insert [B]
    select 1,'A',3,'dd'
    --------------开始查询--------------------------
    DECLARE @aging INT
    DECLARE @unit VARCHAR(2)
    SELECT @aging=aging,@unit=unit
    FROM b
    WHERE type='a'
    SELECT * FROM aDECLARE @sql VARCHAR(max)
    SET @sql='
    UPDATE a
    SET a.endtime=DATEADD('+CAST(@unit AS VARCHAR)+','+CAST(@aging AS VARCHAR)+',a.[createtime])'EXEC( @sql)
    SELECT * FROM a
    ----------------结果----------------------------
    /* 
    id   type createtime              endtime
    ---- ---- ----------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    001  A    2013-10-01 00:00:00.000 NULLid   type createtime              endtime
    ---- ---- ----------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    001  A    2013-10-01 00:00:00.000 2013-10-04 00:00:00.000
    */
      

  2.   


    declare @aging int ,@unit char(2),@sql varchar(200)
    set @aging=3
    set @unit ='dd'
    set @sql='select dateadd('+@unit+','+cast(@aging as varchar(20))+',''2014-01-01'')'
    print @sql
    exec(@sql)select dateadd(dd,3,'2014-01-01')-----------------------
    2014-01-04 00:00:00.000(1 行受影响)
      

  3.   

    update a set a.endtime=convert(varchar(10),dateadd(b.dd,b.aging,a.createtime),23) from tka a join tkb b on a.type=b.type