Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to UPDATE #temptable

CREATE TABLE #TempProducts (
    Id uniqueidentifier,
    ManufacturerId uniqueidentifier,
    Number varchar(50),
    PresentId uniqueidentifier null)

How to UPDATE PresentId field? I have different errors in this:

1) There is already an object named '#TempProducts' in the database.

UPDATE #TempProducts
SET #TempProducts.PresentId = p.Id
FROM #TempProducts JOIN Products p ON (#TempProducts.ManufacturerId = p.ManufacturerId AND #TempProducts.Number = p.Number)
WHERE #TempProducts.Id <> p.Id

2) The multi-part identifier "t.PresentId" could not be bound.

UPDATE #TempProducts
SET t.PresentId = p.Id
FROM #TempProducts t JOIN Products p ON (t.ManufacturerId = p.ManufacturerId AND t.Number = p.Number)
WHERE t.Id <> p.Id
like image 482
FireShock Avatar asked Feb 17 '26 02:02

FireShock


2 Answers

For the Second Error please try:

UPDATE t
SET t.PresentId = p.Id
FROM #TempProducts t JOIN Products p ON (t.ManufacturerId = p.ManufacturerId AND t.Number = p.Number)
WHERE t.Id <> p.Id
like image 199
TechDo Avatar answered Feb 18 '26 16:02

TechDo


UPDATE t
SET t.PresentId = p.Id
FROM #TempProducts t JOIN Products p ON (t.ManufacturerId = p.ManufacturerId AND t.Number = p.Number)
WHERE t.Id <> p.Id

This would be fix for a second error (UPDATE t instead of UPDATE #TempProducts). However, there is no way first query could produce mentioned error.

I am guessing you are executing your CREATE TABLE query again which is producing error because temp table already exists.

You should use a check like this when creating temp tables:

IF (OBJECT_ID('tempdb..#TempProducts') IS NOT NULL) DROP TABLE #TempProducts
CREATE TABLE #TempProducts (
    Id uniqueidentifier,
    ManufacturerId uniqueidentifier,
    Number varchar(50),
    PresentId uniqueidentifier null)
like image 34
Nenad Zivkovic Avatar answered Feb 18 '26 16:02

Nenad Zivkovic