Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - How to Hint an Index on an Update command?

I'm trying to execute the following command to force an update to use a non-clustered index:

 UPDATE Flights 
 SET Airtime=5555678
 WHERE Distance=10000
 OPTION (TABLE HINT(Flights, INDEX (DistanceIndex)))

... and it's erroring:

Msg 8724, Level 16, State 1, Line 75
Cannot execute query. Table-valued or OPENROWSET function 'Flights' cannot be specified in the TABLE HINT clause.

I can't find any clear advice on how the syntax should be properly formed inside the TABLE HINT statement.

Please can anyone advise where I'm going wrong?

like image 472
Jon295087 Avatar asked Jul 26 '14 20:07

Jon295087


2 Answers

Try following:

UPDATE F
SET F.Airtime=5555678
FROM Flights F WITH (INDEX (DistanceIndex))
WHERE F.Distance=10000

or

UPDATE Flights
SET Airtime=5555678
FROM Flights -- this line is added to your initial query
WHERE Distance=10000
OPTION (TABLE HINT(Flights, INDEX (DistanceIndex)))
like image 199
i-one Avatar answered Oct 23 '22 05:10

i-one


@i-one's answer is correct and the recommended way.

You can also use

UPDATE F
SET    Airtime = 5555678
FROM   Flights F
WHERE  Distance = 10000 
OPTION (TABLE HINT(F, INDEX (DistanceIndex)))

But the documentation states

We recommend using the INDEX, FORCESCAN or FORCESEEK table hint as a query hint only in the context of a plan guide.

like image 24
Martin Smith Avatar answered Oct 23 '22 06:10

Martin Smith