Please try the following solution.
It is using SQL Server's XML and XQuery functionality to achieve what you need.
Notable points:
- 1st
CROSS APPLY
is tokenizing columns for each row as XML.
- 2nd
CROSS APPLY
is summarizing values where XML element names (and original column names) are matching a particular naming convention.
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (id INT IDENTITY PRIMARY KEY, Pref_01 INT, Pref_02 INT, Pref_40 INT);
INSERT @tbl (Pref_01, Pref_02, Pref_40) VALUES
(5, 2, 7),
(6, 7, 5);
-- DDL and sample data population, end
SELECT t.*
, [sum-columns-across-the-row]
FROM @tbl AS t
CROSS APPLY (SELECT t.* FOR XML PATH(''), TYPE, ROOT('root')) AS t1(x)
CROSS APPLY (SELECT x.value('sum(/root/*[contains(local-name(), "Pref_")]/text()) cast as xs:integer?', 'INT')) AS t2([sum-columns-across-the-row]);
Output
id |
Pref_01 |
Pref_02 |
Pref_40 |
sum-columns-across-the-row |
1 |
5 |
2 |
7 |
14 |
2 |
6 |
7 |
5 |
18 |