0
DECLARE @EmployeeIds VARCHAR(200)

SELECT @EmployeeIds = ISNULL (@EmployeeIds + ',', '') + CAST(ID AS VARCHAR(5))
FROM tblEmployee
WHERE Gender = 'Male'

PRINT @EmployeeIds 

Do you have any idea how we got the 1,3,4,5,6,9,10 ? I mean here how we got the answer as an array and not like this:

1
3
4
5
6
9
10
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sek
  • 1

1 Answers1

4

How we got the answer as an array?

It isn't an array. It is a comma delimited string. It was generated through assigning to the variable @EmployeeIds multiple times. Once for each row in tblEmployee that matched the WHERE clause.

@EmployeeIds is null to begin with. The first row is encountered and has ID of 1.

  @EmployeeIds= ISNULL (@EmployeeIds + ',', '') + CAST(ID AS VARCHAR(5))
≡ @EmployeeIds= ISNULL (NULL + ',', '') + '1' /*Substituting in variable and column values*/
≡ @EmployeeIds= ISNULL (NULL, '') + '1'
≡ @EmployeeIds= '' + '1'

So @EmployeeIds is 1 after the first row.

The second row is processed and has ID of 3

  @EmployeeIds= ISNULL (@EmployeeIds + ',', '') + CAST(ID AS VARCHAR(5))
≡ @EmployeeIds= ISNULL ('1' + ',', '') + '3' /*Substituting in variable and column values*/
≡ @EmployeeIds= ('1' + ',')  + '3'
≡ @EmployeeIds= '1,3'

And so on. This is not a guaranteed approach to string concatenation. It can and does fail and is specifically warned against by Microsoft.

Some example warnings

Future versions will include a STRING_AGG function. For now the best alternative is XML PATH

Community
  • 1
  • 1
Martin Smith
  • 438,706
  • 87
  • 741
  • 845