Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last comma from dynamic sql

How could i remove the last comma from a part of dynamic query

set @Query += '[A].[ID].&[' + Convert(varchar,SUBSTRING(@string, @start, @end - @start) ) +']&[CAN],[A].[ID].&[' +Convert(varchar,SUBSTRING(@string, @start, @end - @start) ) + ']&[usa],';
like image 232
aman6496 Avatar asked Jan 26 '17 11:01

aman6496


People also ask

How do I remove the last comma in SQL?

To remove all characters after the last comma in the string, you can use SUBSTRING_INDEX().


2 Answers

One common technique uses Left and Len function

set @Query = Left(@Query,len(@Query)-1)

Update : Run the above statement after competition of while loop/Cursor or after framing the entire query

like image 196
Pரதீப் Avatar answered Sep 29 '22 07:09

Pரதீப்


Rephrase your logic and remove the first one using stuff():

set @Query = ',[A].[ID].&[' + . . . ';

Then remove it as:

set @Query = stuff(@Query, 1, 1, '');
like image 25
Gordon Linoff Avatar answered Sep 29 '22 05:09

Gordon Linoff