12 Years, 8 Months too late!
For the cross apply used here, make sure to use it on a unique index (unless you need an array of objects)
-- INIT database
CREATE TABLE Product (
ProductID INT IDENTITY(1, 1),
Preferred_Data_Point INT,
Data_Point_1 VARCHAR(10),
Data_Point_2 VARCHAR(10),
Data_Point_3 VARCHAR(10)
);
INSERT INTO Product(Data_Point_1, Data_Point_2, Data_Point_3) VALUES ('Hello', 'World', '*wave*');
INSERT INTO Product(Data_Point_1, Data_Point_2, Data_Point_3) VALUES ('Hello', 'World', '*wave*');
INSERT INTO Product(Data_Point_1, Data_Point_2, Data_Point_3) VALUES ('Hello', 'World', '*wave*');
-- Dynamic Selection Criteria (Define Column Name) (Useful for views)
SELECT
[Product].ProductID,
JSON_VALUE(ProductJSON.JSON, CONCAT('$.Data_Point_', Product.ProductID)) AS [value]
FROM Product [Product] WITH (NOLOCK)
CROSS APPLY -- 1to1 Cross Apply Row w/ JSON equivalent
(
SELECT (SELECT *
FROM Product [jsonProduct] WITH (NOLOCK)
WHERE jsonProduct.ProductID = Product.ProductID
FOR JSON AUTO, WITHOUT_ARRAY_WRAPPER) [JSON]
) [ProductJSON];
-- More Obvious
INSERT INTO Product(Data_Point_1, Data_Point_2, Data_Point_3, Preferred_Data_Point) VALUES ('Hello', 'World', '*wave*', 2);
INSERT INTO Product(Data_Point_1, Data_Point_2, Data_Point_3, Preferred_Data_Point) VALUES ('Hello', 'World', '*wave*', 3);
INSERT INTO Product(Data_Point_1, Data_Point_2, Data_Point_3, Preferred_Data_Point) VALUES ('Hello', 'World', '*wave*', 1);
-- Select based on rows other column values (same as before, but different)
SELECT
[Product].ProductID,
JSON_VALUE(ProductJSON.JSON, CONCAT('$.Data_Point_', Product.Preferred_Data_Point)) AS [value]
FROM Product [Product] WITH (NOLOCK)
CROSS APPLY -- 1to1 Cross Apply Row w/ JSON equivalent
(
SELECT (SELECT *
FROM Product [jsonProduct] WITH (NOLOCK)
WHERE jsonProduct.ProductID = Product.ProductID
FOR JSON AUTO, WITHOUT_ARRAY_WRAPPER) [JSON]
) [ProductJSON];
Preview here:
SQLFiddle
+ @var1 +
should be+ QUOTENAME(@var1) +
to avoid problems with spaces and other possible special characters in column names. It also helps prevent possible injection issues. Also, If you're composing a comma separated list each individual column name should be passed through QUOTENAME. – Officiary