Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
csdyyr
Starting Member
3 Posts |
Posted - 2009-10-29 : 22:02:25
|
There are two tables with the same struture(ID datatype, COL datatype) except for data type, and I wanted to update the value of column COL to that of ID from the previovs record, the following two statements demonstrate this operation, the output from statement 1 is what I wanted but that of statement 2 is not as expected, I don't know why this would occur.Any advice would be much appreciated!--version: SQL Server 2000 SP4--statement 1:CREATE TABLE T(ID INT, COL INT) --INTINSERT T(ID)SELECT 1 UNION ALLSELECT 2 UNION ALLSELECT 3CREATE CLUSTERED INDEX IDX_ID ON T(ID)DECLARE @COL INT, @COL2 INTUPDATE T SET @COL=@COL2, @COL2=ID, COL=@COLSELECT * FROM TDROP TABLE T/*ID COL ----------- ----------- 1 NULL2 13 2*/----statement 2:CREATE TABLE T2(ID VARCHAR(8), COL VARCHAR(8)) --VARCHAR(8)INSERT T2(ID)SELECT '00000001' UNION ALLSELECT '00000002' UNION ALLSELECT '00000003'CREATE CLUSTERED INDEX IDX_ID ON T2(ID)DECLARE @COL VARCHAR(8), @COL2 VARCHAR(8)UPDATE T2 SET @COL=@COL2, @COL2=ID, COL=@COLSELECT * FROM T2DROP TABLE T2/*ID COL -------- -------- 00000001 NULL00000002 0000000200000003 00000003*/ |
|
russell
Pyro-ma-ni-yak
5072 Posts |
Posted - 2009-10-30 : 01:25:53
|
[code]UPDATE tSET col = x.idFROM t2 tJOIN t2 xOn t.id = x.id + 1[/code] |
|
|
csdyyr
Starting Member
3 Posts |
Posted - 2009-10-31 : 04:01:52
|
russell,Thank you for your reply!And here is an explanation for my question: Because @COL of VARCHAR(8) data type is a reference type variable and @COL of INT data type is a value type variable. So when the following query was executed,UPDATE T SET @COL=@COL2, @COL2=ID, COL=@COLthe execution steps like:--step 1:Row 1@COL=@COL2 =>@COL=NULL@COL2=ID =>@COL2='00000001'COL=@COL =>COL=NULL ?--step 2:Row 2@COL=@COL2 =>I expected it should be: @COL='00000001'@COL2=ID =>@COL2='00000002'COL=@COL =>I expected COL='00000001', but @COL refers to @COL2, so COL='00000002' The theory as descriped in step 2 best explained my question, but why it didn't apply to step 1, it's still a question to me. |
|
|
csdyyr
Starting Member
3 Posts |
Posted - 2009-10-31 : 22:14:18
|
Here is a solution:UPDATE T2 SET @COL=CAST(@COL2+'' AS VARCHAR(8)), @COL2=ID, COL=@COLBut this update technique is not reliable, it's not recommended to use. |
|
|
|
|
|
|
|