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 + '.

2
  • There are better ways than using cursors for concatenating values from several rows into a comma-separated list; see e.g. stackoverflow.com/questions/194852/…. Commented Mar 27, 2015 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. Commented Mar 27, 2015 at 14:21

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Thx it was so simple :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.