0
Declare @i int;
declare @stringOfGuids nvarchar(max)='''70173C2D-0B8E-4043-BD14-665D5DCCF112'',''B0B7445C-DF50-4D49-BD4E-B74958FB0618''
,''70173C2D-0B8E-4043-BD14-665D5DCCF112''';

I have this string and I need to count the number of available guid which is three.

How can I get it in a Integer variable?

Something like this ?

select @i = count(@stringOfGuids)

but it returns 1, I need three as available guids are 3.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rajesh
  • 119
  • 1
  • 4
  • 12

2 Answers2

4

Count the number of commas and add 1.

SELECT Len(@stringOfGuids ) - Len(Replace( @stringOfGuids , ',', '')) + 1

The counting is from this answer.

Community
  • 1
  • 1
Marko Juvančič
  • 5,792
  • 1
  • 25
  • 41
  • that's ingenious! He might want to count the quotes that way though, cos he's got a colon at the end I think - oh yeah sorry, add 1 – Cato Jul 27 '16 at 08:55
  • yes, excellent Marko, it worked for me ,, thnx alot..good decent solution.. – Rajesh Jul 27 '16 at 08:56
1
Declare @i int;

declare @stringOfGuids nvarchar(max)='''70173C2D-0B8E-4043-BD14-665D5DCCF112'',''B0B7445C-DF50-4D49-BD4E-B74958FB0618'' ,''70173C2D-0B8E-4043-BD14-665D5DCCF112''';

declare @cnt int = 0;
declare @pos int = 1;

while charindex('''', @stringOfGuids, @pos) > 0
    SELECT @pos =  charindex('''', @stringOfGuids, @pos) + 1, @CNT = @CNT + 1;



SELECT @CNT / 2;
Cato
  • 3,652
  • 9
  • 12