3

I have problem inserting sql script in the variable.I have this code

   declare @result_var varchar(max);
SET @result_var=''; 
DECLARE @cursor CURSOR, 
@name   VARCHAR(100) 
SET @cursor = CURSOR 
FOR SELECT [NAME] 
    FROM   [iflvs08].mds.mdm.lv_budget_employee
OPEN @cursor
FETCH next FROM @cursor INTO @name 
WHILE @@FETCH_STATUS = 0 
  BEGIN 
      IF (RIGHT(@Name, 1) = ' ')
        begin
            IF( Len(@result_var) > 1 ) 
              SET @result_var=@result_var + ','+ @name 
            ELSE 
              SET @result_var=@name 
        END
      FETCH next FROM @cursor INTO @name 
  END

I want to insert into variable it but when try to insert it like this

set @sql='code here'

It get confuse whit this ' symbol and dont insert it I always get error like this Msg 102, Level 15, State 1, Line 13 Incorrect syntax near ' begin IF( Len(@result_var) > 1 ) SET @result_var=@result_var + '.

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
Nils Ozols
  • 41
  • 2
  • There are better ways than using cursors for concatenating values from several rows into a comma-separated list; see e.g. http://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string. – stakx - no longer contributing Mar 27 '15 at 14:21
  • What are you really trying to do here? Cursors are very poor performance wise and should be used only in certain situations. Data manipulation is not one of those times. – Sean Lange Mar 27 '15 at 14:21

1 Answers1

3

basically you have to replace all ' symbols with ''

set @sql = '

  declare @result_var varchar(max);
SET @result_var=''''; 
DECLARE @cursor CURSOR, 
@name   VARCHAR(100) 
SET @cursor = CURSOR 
FOR SELECT [NAME] 
    FROM   [iflvs08].mds.mdm.lv_budget_employee
OPEN @cursor
FETCH next FROM @cursor INTO @name 
WHILE @@FETCH_STATUS = 0 
  BEGIN 
      IF (RIGHT(@Name, 1) = '' '')
        begin
            IF( Len(@result_var) > 1 ) 
              SET @result_var=@result_var + '',''+ @name 
            ELSE 
              SET @result_var=@name 
        END
      FETCH next FROM @cursor INTO @name 
  END'
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197