patternsqlMinor
Optimize this SQL query for performance
Viewed 0 times
thissqlqueryforoptimizeperformance
Problem
I'm trying to optimize the following statement:
The statement produces a value like
I would like to optimize this in terms of removing redundant cast statements and providing an efficient way to concatenate the strings and integers.
'VI'+CAST(month(GETDATE()) AS NVARCHAR)+'/'+CAST(year(GETDATE()) AS NVARCHAR)
+'/00000' +CAST(@number+1 AS VARCHAR)The statement produces a value like
VI1/2011/000002 if the @number parameter is 1. I would like to optimize this in terms of removing redundant cast statements and providing an efficient way to concatenate the strings and integers.
Solution
If you find yourself frequently performing this conversion as data gets selected out, try using a persisted calculated field instead. It gets added to the table, and SQL Server automatically calculates it whenever the data is inserted or updated. You pay the calculation penalty once - just once - and then it's less CPU whenever the data is selected back out. You can even put an index on it if you find yourself filtering queries with that field.
Context
StackExchange Database Administrators Q#861, answer score: 7
Revisions (0)
No revisions yet.