Tuesday, 10 November 2009

Assigning variables from multiple records in a table

It may be required to assign values to multiple variables from multiple rows in a table.

Consider the following table:





configNameconfigValue
configOne1
configTwo2
configThree3


If we wanted to assign:
  • @configOne to the configValue where configName = 'configOne'
  • @configTwo to the configValue where configName = 'configTwo'
  • etc.

We could achieve this with the following multiple select statements:
  • SELECT @configOne = configValue FROM TableName WHERE configName = 'configOne'
  • SELECT @configTwo = configValue FROM TableName WHERE configName = 'configTwo'
  • SELECT @configThree = configValue FROM TableName WHERE configName = 'configThree'

This of course requires 3 seperate reads on the table, a more efficient method to assign these variables would be to use a pivot table query.
i.e.
SELECT @configOne = [configOne]
, @configTwo = [configTwo]
, @configThree = [configThree]
FROM
(SELECT configName ,configValue
FROM TableName
WHERE configName IN ('configOne','configTwo','configThree')) AS p
PIVOT(
MAX(configValue)
FOR configName IN ( [configOne], [configTwo], [configThree])) AS pvt