大家好,沒事寫篇文章,看標題一定嚇死你們,好象我在SQL方面有很高的造詣似的,其實只是一時靈光咋現(xiàn),寫了一句自己認為很有水平的UPDATE語句而已
,并且可以在set中為變量付值,也就是下面這樣
update table1 set @test_vr = 1,table1.col_1 = 1,table1.col_2 = 2......
他會逐行的順序的干這個事情:@test_vr變?yōu)?,然后table1.col_1變1,然后table1.col_2變2.....
開始并不覺得有什么意思,不就是付了個變量嗎???就在這時問題出現(xiàn)了,以前寫過用OPENDATASOURCE將EXECL表格數(shù)據(jù)轉(zhuǎn)到SQL里面來的過程,運行了發(fā)現(xiàn)有兩列的數(shù)據(jù)換位了,后來是在前臺將兩列數(shù)據(jù)提出,經(jīng)過中間變量轉(zhuǎn)來轉(zhuǎn)去搞定的,現(xiàn)在既然知道可以給變量在更新的時候付值,那我可不可以給他付上一個列值呢???這樣他就可以起個中間過度的作用,以便交換兩列的信息呢???形式如下
update table1
set @ test_vr = table1.col_1,
table1.col_1 = table1.col_2,
table1.col_2 = @ test_vr
如果可以的話就能一條SQL搞定兩列的數(shù)據(jù)交換了
想法出來了,馬上測試,頓時我象加了興奮劑的機槍兵一樣,開始在鍵盤上狂打,我打打打。。。打打打。。。,結(jié)果如下:
create table #table1
(k1 int identity,
col_1 float default (rand() * 1000),
col_2 float default (rand() * 1000)
)
insert #table1 default values
insert #table1 default values
insert #table1 default values
insert #table1 default values
insert #table1 default values
insert #table1 default values
insert #table1 default values
select * from #table1
declare @temp float
UPDATE #table1
SET @temp = col_1,
col_1 = col_2,
col_2 = @temp
select * from #table1
drop table #table1
/*
更新前結(jié)果
1 941.36949447026325 233.37477802301783
2 923.1058159060284 192.20059842338031
3 643.87548560639073 756.58847730848083
4 918.08798431334401 602.32691571853718
5 535.33978217043614 783.31296232037164
6 227.3707647382418 407.77376660523362
7 386.33853691324845 573.14291947875824
更新后結(jié)果
1 233.37477802301783 941.36949447026325
2 192.20059842338031 923.1058159060284
3 756.58847730848083 643.87548560639073
4 602.32691571853718 918.08798431334401
5 783.31296232037164 535.33978217043614
6 407.77376660523362 227.3707647382418
7 573.14291947875824 386.33853691324845
*/
大家應(yīng)該看明白了吧,我覺得是很奇妙的,好了,今天不熬夜,也不嗑安眠藥了,拉燈,告鐘,睡覺先!??!
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。