I would like to be able to update a table at once, instead of multiple statements and I don't want to make a temporary table.
To test this, I made this table:
USE [SomeSchema]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [SomeSchema].[TestTable](
[Id] [int] IDENTITY(1,1) NOT NULL,
[TextField] [varchar](250) NULL,
[updateField] [varchar](20) NULL,
CONSTRAINT [Pk_TestTable_Id] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [Idx_TestTable] UNIQUE NONCLUSTERED
(
[TextField] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
I tried to combine these two answers (https://stackoverflow.com/a/57965771 and https://stackoverflow.com/a/32431922/369122) into a working statement.
My last try:
WITH NewData AS
(
SELECT * FROM ( VALUES ('abc', 'A'),('def','d'),('ghi','g'))
x
(TextField, updateField)
)
update [SomeSchema].[TestTable]
set _a.updateField= _b.updateField
from
[SomeSchema].[TestTable] _a,
NewData _b
where _a.TextField=_b.TextField
Gave this error: Msg 4104, Level 16, State 1, Line 22 The multi-part identifier "_a.updateField" could not be bound.
Any suggestions? For the record; this is just a test. In practice I need to be able to join multiple columns to update one or more columns. thanks,
Matthijs
@larnu's answer did the job:
"As for the problem, replace update [SomeSchema].[TestTable] with update _a. You're referencing a table in your FROM as the column to UPDATE, but the table your updating is defined as a different instance of [TestTable]"
WITH NewData AS
(
SELECT * FROM ( VALUES ('abc', 'a'),('def','d'),('ghi','g'))
x
(TextField, updateField)
)
update _tt
set _tt.updateField= _nd.updateField
from
[SomeSchema].[TestTable] _tt
left join
NewData _nd
on _tt.TextField=_nd.TextField