Reputation: 1945
How can I optimize the below query. You can see the only difference is with the Amount column.
INSERT INTO TableA
( Name, Amount, Cityname)
(SELECT Name,(Expense *15),CityName
FROM TableB B JOIN TableC C ON B.Id = C.FID AND B.Number = E23)
UNION
(SELECT Name,(Expense *25),CityName
FROM TableB B JOIN TableC C ON B.Id = C.FID AND B.Number = E23)
Are there any better ways to do this?
Upvotes: 1
Views: 84
Reputation: 883
Try this query --
DECLARE @Name VARCHAR(255)
,@Expense1 INT
,@Expense2 INT
,@CityName VARCHAR(255)
SELECT @Name = [Name]
,@Expense1 = (Expense * 15)
,@Expense2 = (Expense * 15)
,@CityName = CityName
FROM TableB B
JOIN TableC C ON B.Id = C.FID
AND B.Number = E23
INSERT INTO TableA (
NAME
,Amount
,Cityname
)
VALUES (
@Name
,@Expense1
,@CityName
)
,(
@Name
,@Expense2
,@CityName
)
And also you should consider the two points mentioned by @TabAlleman in the answer. I'm just repeating here what he said --
Upvotes: 0
Reputation: 1269853
I would suggest:
INSERT INTO TableA ( Name, Amount, Cityname)
SELECT Name, (Expense * v.val), CityName
FROM TableB B JOIN
TableC C
ON B.Id = C.FID AND B.Number = E23 CROSS APPLY
(VALUES (15), (25)) c(val);
This is not exactly the same, because it does not reduce duplicates. But, I doubt that you really want to do that.
Then, you want indexes on TableB(Number, ID)
and TableC(FID)
.
Upvotes: 4
Reputation: 31785
Two things you can do.
Covering Indexes. Index TableB on Id,Number. Index TableC on FID.
UNION ALL. If you aren't expecting any duplicate data that needs to be eliminated, then UNION ALL performs faster than UNION, since it won't do the extra work of checking for duplicates.
Upvotes: 1