表A:
id type createtime endtime
001 A 2013-10-1
表B:
id type aging unit
1 A 3 dd
现在更新A中的endTime
从B中读出type 为A 的然后在createdtime的基础上加上B表中的aging 格式为B表中的unit
------解决方案--------------------
update a set endtime = dateadd(b.unit,b.aging,a.createtime)
from 表A a ,表B b where a.type =b.type
没试,不知道这样行不。
不行就定义一个字符串,然后exec(字符串)
------解决方案--------------------
----------------------------------------------------------------
-- 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 a
DECLARE @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 NULL
id type createtime endtime
---- ---- ----------------------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
001 A 2013-10-01 00:00:00.000 2013-10-04 00:00:00.000
*/
------解决方案--------------------
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