-4

我想从这个动态 sql 中删除引号,所以它只是一个脚本。

set @sqlDNB= '
 SELECT DISTINCT
                   Null CustomerID
                   ,EntityID MCVID
                   ,business_name CustomerName
                   ,physical_City +  ',' + physical_state +  '' + cast(physical_zip as varchar(7)) Address
                   ,'' RM
                   ,'' SubGroup
                   ,'' HierarchyType
                   ,'' status 
                   ,DNB.dunsnum DunsNumber
                   ,'DNB' Source
              from SOR.T_DunAndBradstreet DNB with (nolock)
              left outer join SOR.T_McvDuns MCVDUNS with (nolock)
              on DNB.dunsnum  = MCVDUNS.DunsNumber
                +
 case
 when @p_SearchMethod ='BeginsWith' and @p_CustomerName !='' then 'and business_name like ''' + @p_CustomerName + ''' '
 when @p_SearchMethod ='Contains' and @p_CustomerName !=''  then 'and Contains (business_name,''"' + @p_CustomerName + '"'')'
 when @p_SearchMethod ='Exact' and @p_CustomerName !=''  then  'and business_name =''' + @p_CustomerName + ''' ' 
 else
 ''
end 

+ ' where not exists 
(select dunsnumber from sor.T_Customer customer where customer.DUNSnumber = DNB.dunsnum '
+  
case
 when @p_SearchMethod ='BeginsWith' and @p_CustomerName !='' then 'and customer.Name like ''' + @p_CustomerName + ''' '
 when @p_SearchMethod ='Contains' and @p_CustomerName !=''  then 'and Contains (customer.Name,''"' + @p_CustomerName + '"'')'
 when @p_SearchMethod ='Exact' and @p_CustomerName !=''  then  'and customer.Name =''' + @p_CustomerName + ''' ' 
 else
 ''
end 

if @p_TIN_SSN !='' 
begin
set  @sqlDNB =  @sqlDNB + ' and customer.TINorSSN =''' + @p_TIN_SSN + ''' ' 
end
if  @p_CustomerID !='' 
begin
set  @sqlDNB =  @sqlDNB + ' and customer.[MCVID] =''' + cast(@p_CustomerID as varchar(20)) + '''  '  
end 
set  @sqlDNB =  @sqlDNB + ')'
4

2 回答 2

1

从以下代码中删除任何单引号将导致错误:

'and business_name like ''' + @p_CustomerName + ''' '

当您''在 SQL 中看到字符串内部时,它表示单个'. 例如

declare @test varchar(12)
set @test = 'don''t'
select @test

将返回don't

因此,从您提到的代码块中删除任何单引号将使您like中断。

希望这是有道理的。

于 2013-03-22T23:54:35.253 回答
1

在 SQL Server Management Studio 中“调试”此类脚本的便捷方法如下:

DECLARE @sqlDNB nvarchar(max);

set @sqlDNB = <your script here>;

PRINT @sqlDNB;

如果您运行此程序,您将收到可用于修改脚本的特定错误消息。最后,打印的字符串是 SQL 脚本,您也可以复制和测试它。

于 2013-03-23T00:00:25.243 回答