Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quicker way to update all rows in a SQL Server table

Is there a more efficient way to write this code? Or with less code?

SELECT * 
INTO #Temp 
FROM testtemplate

Declare @id INT
Declare @name VARCHAR(127)

WHILE (SELECT Count(*) FROM #Temp) > 0 
BEGIN 

    SELECT TOP 1 @id = testtemplateid FROM #Temp
    SELECT TOP 1 @name = name FROM #Temp

    UPDATE testtemplate
    SET testtemplate.vendortestcode = (SELECT test_code FROM test_code_lookup WHERE test_name = @name)
    WHERE testtemplateid = @id

     --finish processing 
    DELETE #Temp Where testtemplateid = @id
END
DROP TABLE #Temp
like image 992
MacGyver Avatar asked Dec 19 '11 15:12

MacGyver


3 Answers

You can do this in a single UPDATE with no need to loop.

UPDATE tt
    SET vendortestcode = tcl.test_code
    FROM testtemplate tt
        INNER JOIN test_code_lookup tcl
            ON tt.name = tcl.test_name
like image 53
Joe Stefanelli Avatar answered Oct 10 '22 23:10

Joe Stefanelli


You could try a single update like this:

UPDATE A
SET A.vendortestcode = B.test_code
FROM testtemplate A
INNER JOIN test_code_lookup B
ON A.name = B.test_name

Also, the way you are doing it now is wrong, since you are taking a TOP 1 Id and a TOP 1 name in two separate querys, without an ORDER BY, so its not sure that you are taking the right name for your ID.

like image 41
Lamak Avatar answered Oct 10 '22 23:10

Lamak


You could write a function to update vendortestcode. Then your code reduces to one SQL statement:

update testtemplate set vendortestcode = dbo.get_test_code_from_name(name)
like image 40
jeff.eynon Avatar answered Oct 10 '22 23:10

jeff.eynon