2014-08-31 84 views
0
declare 
@Kol as cursor 
if(len(@to_num)<>0) 
    begin 
     if(len(@to_num)<18) 
     begin 
      set @payam='error'    
      return 
     end 
     else 
     begin 
      if(LTRIM(RTRIM(@from_num)) = LTRIM(RTRIM(@to_num))) 
       set @StrSQL = 'Mashaghel.Code='' & LTRIM(RTRIM(@to_num)) & ''' 
      else 
      begin 
       if (LTRIM(RTRIM(@StrSQL)) = '') 
        set @StrSQL = 'Mashaghel.Code<='' & LTRIM(RTRIM(to_num)) & ''' 
       else 
        set @StrSQL = @StrSQL + ' AND Mashaghel.Code<='' & LTRIM(RTRIM(@to_num)) & ''' 
      end 

     end   
    end 

set @Kol=cursor for SELECT * FROM AvarezMashaghel WHERE am in (SELECT Code FROM Mashaghel Where + @StrSQL+ ) 

此代碼錯誤說::CONCAT SQL字符串到sql命令

set @Kol=cursor for SELECT * FROM AvarezMashaghel WHERE am in (SELECT Code FROM Mashaghel Where + @StrSQL+ ) 

An expression of non-boolean type specified in a context where a condition is expected

我如何添加字符串StrSQL到SQL命令?

+0

錯誤發生在哪條線上?你爲什麼問這個問題6次? – 2014-08-31 12:01:37

+1

http://stackoverflow.com/questions/1045880/using-a-cursor-with-dynamic-sql-in-a-stored-procedure – Laurence 2014-08-31 12:06:16

+0

@ElecticLIama:set @ Kol = cursor for SELECT * FROM AvarezMashaghel WHERE am in( SELECT代碼FROM Mashaghel Where + @ StrSQL +) – ashkufaraz 2014-08-31 12:08:12

回答

1

您的主要問題是無法將SQL命令與表示SQL命令的字符串結合使用。這(來自您的代碼)只是不會工作。

SELECT Code FROM Mashaghel Where + @StrSQL -- won't work 

(你的錯誤消息告訴您表達+ @StrSQL不計算爲true或false:它的計算結果爲一個字符串。)

只有這樣,才能動態地建立一個表達,然後執行它是動態生成所有的表情,就像這樣:

DECLARE @sql nvarchar(200) 
SET @sql = 'SELECT Code FROM Mashaghel Where ' + @StrSQL 
exec @sql 

但我高度懷疑,將與光標的工作,雖然我可能是錯的。自從我使用光標以來已經很長時間了。

你可以嘗試這樣的事:

set @Kol=cursor for 
    SELECT * FROM AvarezMashaghel 
      WHERE (LTRIM(RTRIM(@from_num)) = LTRIM(RTRIM(@to_num))) 
      AND Mashaghel.Code= LTRIM(RTRIM(@to_num))) 
      OR (Mashaghel.Code<=LTRIM(RTRIM(to_num))) 

這不會是迅速的,但它可能會工作。

0
set @StrSQL = 'Declare users_cursor CURSOR FOR SELECT Code FROM Mashaghel Where ' + @StrSQL+' 

exec sp_executesql @StrSQL 


FETCH NEXT FROM users_cursor 
INTO ... 

WHILE @@FETCH_STATUS = 0 
....