删除我的sql语句中的第一个单词

时间:2013-12-04 13:32:34

标签: cursor trim sql-function

我在Microsoft SQL中有一个创建自动sql行的函数,一个(Querybuilder)。在这种情况下,我在我的一个游标中有这一行看起来像这样:

  set @Query = @Query + ' AND ('+ (case when(@CountryDelivery = 1) then 'Delivery' else     'pickup' end) +'.CountryUK '+ (case(@CountryExcl) when 1 then ' <> ''' else ' = ''' end) + @country + ''')'    

这会使我的结果看起来像: “AND(country ='USA')AND(Country ='Canada')......”ETC,全部取决于用户在其数据表中存储的国家数量。

我的挑战是我希望在查询开始时删除“AND”语句,但如果用户添加更多国家/地区则不会。

这是我的全部功能:

SET @Query = @Query + ' ('  
declare Accountring_Country1Cursor Cursor for 
        select Country, Exclude, IsDelivery, ID from dbo.Accounting_Country1 where Service_ID = @Service_ID        
OPEN Accountring_Country1Cursor
FETCH NEXT FROM Accountring_Country1Cursor 
INTO @country, @CountryExcl, @CountryDelivery, @country_ID
WHILE @@FETCH_STATUS = 0
BEGIN
set @Query = @Query + ' AND ('+ (case when(@CountryDelivery = 1) then 'Delivery'     else 'pickup' end) +'.CountryUK '+ (case(@CountryExcl) when 1 then ' <> ''' else ' = ''' end) + @country + ''')'    
    FETCH NEXT FROM Accountring_Country1Cursor 
INTO @country, @CountryExcl, @CountryDelivery,@country_ID
END 
CLOSE Accountring_Country1Cursor
DEALLOCATE Accountring_Country1Cursor 
SET @Query = @Query + ') '              
RETURN @Query

     END

1 个答案:

答案 0 :(得分:1)

试试这个:

declare @filter varchar(max);
set @filter = '(1 = 1)';

declare Accountring_Country1Cursor Cursor for select Country, Exclude, IsDelivery, ID from dbo.Accounting_Country1 where Service_ID = @Service_ID        
OPEN Accountring_Country1Cursor

FETCH NEXT FROM Accountring_Country1Cursor INTO @country, @CountryExcl, @CountryDelivery, @country_ID
WHILE @@FETCH_STATUS = 0
BEGIN
    set @filter = @filter + ' AND ('+ (case when(@CountryDelivery = 1) then 'Delivery'     else 'pickup' end) +'.CountryUK '+ (case(@CountryExcl) when 1 then ' <> ''' else ' = ''' end) + @country + ''')'    
    FETCH NEXT FROM Accountring_Country1Cursor INTO @country, @CountryExcl, @CountryDelivery,@country_ID
END 

CLOSE Accountring_Country1Cursor
DEALLOCATE Accountring_Country1Cursor 

SET @Query = @Query + '(' + @filter + ') '              
RETURN @Query

基本上,过滤器的默认值是 true 。然后你总是可以添加一个新的'AND(something)',因为它将是有效的SQL。在构建过滤器之后,您只需将其同时附加到@Query变量即可。

或者,以更简单的方式,您可以获取最终查询的子字符串:

set @Query = '(' + substring(@Query, 4, len(@Query))

或者,稍微复杂但多功能:

set @Query = substring(@Query, 0, 1) + substring(@Query, 4, len(@Query))