日期:2014-05-16 浏览次数:20591 次
update a set endtime = dateadd(b.unit,b.aging,a.createtime)
from 表A a ,表B b where a.type =b.type
----------------------------------------------------------------
-- 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
*/