Try to accomplish your excepted output by using COALESCE
;
Create a sample table for testing purpose
CREATE TABLE SampleData (id INT ,store INT ,value NVARCHAR(50))
INSERT INTO SampleData VALUES (1 ,9921 ,'NOK')
INSERT INTO SampleData VALUES (2 ,9921 ,'NOK1')
INSERT INTO SampleData VALUES (3 ,9921 ,'NOK2')
Create a Scalar-Valued Function
Alter FUNCTION fun_GetCombinedData
(
@store int
)
RETURNS nvarchar(max)
AS
BEGIN
-- Declare the return variable here
DECLARE @CombineValue nvarchar(max)
SELECT @CombineValue = COALESCE(@CombineValue + ', ', '') + value
FROM SampleData where store=@store
RETURN @CombineValue
END
GO
Final Query,
SELECT store
,dbo.fun_GetCombinedData(store) AS value
FROM SampleData
GROUP BY store
Expected Output:
store | value
------------------------
9921 | NOK,NOK1,NOK2
This is one of the way to simplify your select query.