首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

SQL記錄篩選 語句怎樣寫解决方案

2012-03-17 
SQL記錄篩選 語句怎樣寫CREATETABLET1(T1DHVARCHAR(10),PHVARCHAR(20),SLNumeric(9,4))CREATETABLET2(T2DH

SQL記錄篩選 語句怎樣寫
CREATE   TABLE   T1(
T1DH   VARCHAR(10),
PH   VARCHAR(20),
SL   Numeric(9,4)   )

CREATE   TABLE   T2(
T2DH   VARCHAR(10),
PH   VARCHAR(20),
SL   Numeric(9,4)   )

INSERT     INTO   T1  
SELECT   'T1A1 ', 'A ', '10 '
UNION   ALL
SELECT   'T1A1 ', 'B ', '5 '
UNION     ALL
SELECT   'T1A2 ', 'B ', '5 '
UNION   ALL
SELECT   'T1A2 ', 'C ', '5 '

INSERT   INTO   T2
SELECT   'T2A1 ', 'A ', '10 '
UNION   ALL
SELECT   'T2A1 ', 'B ', '5 '
UNION   ALL
SELECT   'T2A1 ', 'C ', '5 '
UNION   ALL
SELECT   'T2A2 ', 'B ', '5 '
UNION   ALL
SELECT   'T2A2 ', 'C ', '5 '

SELECT   *   FROM   T1
SELECT   *   FROM   T2
如何將   T2中的   'T2A1 '   , 'C ', '5 '     通過一條語句插入到T1中

insert   INTO   t1(T1DH,PH,SL)
SELECT   T1.T1DH,T2.PH,T2.SL
FROM   T2,T1
WHERE   T2DH= 'T2A1 '   AND   T1DH= 'T1A1 '       AND   NOT   EXISTS(SELECT   *   FROM   T1,T2   WHERE   T1DH= 'T1A1 '   AND   T2DH= 'T2A1 '   AND   T1.PH=T2.PH)
使t1中增加一條 'T1A1 ', 'C ', '5 '的記錄?



[解决办法]
insert T1
select * from T2 as tmp
where T2DH= 'T2A1 ' and not exists
(select 1 from T1 where T1DH= 'T1A1 ' and PH=tmp.PH)

select * from T1

--result
T1DH PH SL
---------- -------------------- -----------
T1A1 A 10.0000
T1A1 B 5.0000
T1A2 B 5.0000
T1A2 C 5.0000
T2A1 C 5.0000

(5 row(s) affected)
[解决办法]
marco08(天道酬勤)
 感謝你的回復,確實是高手。

热点排行