Hello,
I was just trying to figure out the best options we can choose with when we come across a scenario where we need to use a Temp Table/Table Variable/Create a Temp Table on the fly.
However, I could not see any big difference in using those options. As per my understanding using a table variable is more convenient if the query logic is small and the result set also will be comparatively small.Creating a temp table is also an easy option but it takes much time and we can not create any indexes on it. I am working on a query optimization task where in plenty of temp tables are used and the query takes more than five minutes to execute. We have created few indexes and all in few tables and reduced the query execution time up to 2 mnts.Can anyone give me more suggestions on it. I have gone through various articles about it and came to know that there is no one solution for this and I am aware of the basic criteria like use Set No count on, Order the table in which the indexes are created, Do not use Select * instead use only columns which are really required, Create Indexes and all. Other than these I am stuck with the usage of temp tables. There are some limitations where I can convert all the Temp table logic to CTE (I am not saying its not possible, I really dont have time to spend for the conversion). Any suggestions are welcome.
Actual Query
select Code,dbo.GetTranslatedText(Name,'en-US')as Name from ProductionResponse.ProductionResponse
00.00.02 | 5225 rows |
With Table Variable
DECLARE @GeneralTABLE(Code NVarchar(Max),NameNVarchar(Max))
INSERTINTO @General
select Code,dbo.GetTranslatedText(Name,'en-US')AS Name from ProductionResponse.ProductionResponse
select*from @General
00.00.03 | 5225 rows |
With an Identity Column
DECLARE @GeneralTABLE(Id INTIDENTITY(1,1),Code NVarchar(Max),NameNVarchar(Max))
INSERTINTO @General
select Code,dbo.GetTranslatedText(Name,'en-US')AS Number from ProductionResponse.ProductionResponse
select*from @General
00.00.04 | 5225 rows |
With Temp Table:
CREATETABLE #General(IdINTIDENTITY(1,1)PRIMARYKEY,CodeNVarchar(Max),NameNVarchar(Max))
INSERTINTO #General
select Code,dbo.GetTranslatedText(Name,'en-US')as Name from ProductionResponse.ProductionResponse
select*from #General
DROPTABLE #General
00.00.04 | 5225 rows |
With Temp Table on the Fly
SELECT G.Code,G.NameINTO #General
FROM
(
select Code,dbo.GetTranslatedText(Name,'en-US')as Name from ProductionResponse.ProductionResponse
)G
select*from #General
00.00.04 | 5225 rows |