在变量中插入整个sql脚本

时间:2015-03-27 14:16:10

标签: sql sql-server tsql

我在变量中插入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

我想插入变量,但是当尝试像这样插入

set @sql='code here'

它会让这个'符号变得混乱,不要插入它 我总是得到这样的错误 Msg 102,Level 15,State 1,Line 13 '附近的语法不正确'         开始             IF(Len(@result_var)> 1)               SET @ result_var = @ result_var +'。

1 个答案:

答案 0 :(得分:3)

基本上您必须将所有'符号替换为''

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'