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 |
|
donjt81
Starting Member
11 Posts |
Posted - 2012-05-25 : 13:48:49
|
| My table looks like this right nowCustomerID TechID1__________11__________21__________32__________53__________23__________34__________25__________2This is what I am trying to do. I have introduced a new TechType (in a different table) with TechID = 6. For every customer that has TechID of 2, I want to also add TechID 6. so in the above scenario my table would look like this.CustomerID TechID1__________11__________21__________31__________62__________53__________23__________33__________64__________24__________65__________25__________6I am often faced with this type of insert and I somehow make it work with #temptables etc. but there has to be an elegant way of doing this. Can anyone help please. |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2012-05-25 : 13:56:49
|
| Don't knwo about elegant, but...DECLARE @table Table (CustomerID int,TechID int)INSERT INTO @tableVALUES(1,1),(1,2),(1,3),(2,5),(3,2),(3,3),(4,2),(5,2)select * from @tableINSERT INTO @tableSELECT customerID,6FROM @table t1WHERE exists(select * from @table t2 where t1.CustomerID = t2.CustomerID and t1.TechID =2)select * from @table order by 1,2JimEveryday I learn something that somebody else already knew |
 |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2012-05-25 : 13:58:19
|
INSERT myTable(CustomerID, TechID)SELECT CustomerID, 6 AS TechIDFROM myTable AWHERE TechID=2 AND NOT EXISTS(SELECT * FROM myTable WHERE CustomerID=A.CustomerID AND TechID=6) |
 |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2012-05-25 : 14:09:47
|
And I took the time to include the sample data! JimEveryday I learn something that somebody else already knew |
 |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2012-05-25 : 14:18:50
|
Go ahead, rub it in. |
 |
|
|
|
|
|
|
|