如何在sql中用“','”替换符号“,”?

时间:2014-02-10 06:42:44

标签: sql-server tsql

我正在编写一个SQL查询,它必须将,替换为','到正在传递的字符串。传递的字符串就像jack,john,tony,但输出的结果只是列表的空表。

你能为此提供答案。

CREATE PROCEDURE [dbo].[usp_GetBillingSystem]
(
@BillingCode VARCHAR(300)
)
AS
BEGIN 
declare @ListOfPlanID varchar(30)
declare  @trimmed varchar(30)
declare  @replaced varchar(30)
set @ListOfPlanID =@BillingCode


If  IsNull(@ListOfPlanID,'')='' return 
If LEN(@ListOfPlanID)=0 return 
SET @trimmed=LTRIM(RTRIM(@ListOfPlanID))
set @replaced=''''+REPLACE(@trimmed,',',''',''')+''''   
select * from BillingSystem where BillingCode IN (@replaced)
END  

在vb.net中,我用这种方式从上面的sql查询中编写了获取数据表的代码

Public Function getBillingSystemAttributesInfo(ByVal ConnectionString As String, ByVal                      BillingCode As String) As DataTable
Dim conn As SqlConnection
Dim sqlcmd As SqlCommand
Dim dtBillingSystem As DataTable
Try
conn = New SqlConnection(ConnectionString)
conn.Open()
sqlcmd = New SqlCommand("usp_GetBillingSystem", conn)
With sqlcmd

.CommandType = CommandType.StoredProcedure


 .Parameters.Add("@BillingSystemCode", SqlDbType.VarChar, 300)
 .Parameters("@BillingSystemCode").Value = BillingSystemCode

  dataadapter = New SqlDataAdapter()
  dataadapter.SelectCommand = sqlcmd
  dtBillingSystem = New DataTable("BillingSystem")
  dataadapter.Fill(dtBillingSystem)
   End With
   Catch ex As Exception
    Throw ex
    Finally
    conn.Close()
    sqlcmd = Nothing
    End Try
    Return dtBillingSystem
End Function

3 个答案:

答案 0 :(得分:1)

问题是你不能将变量传递给IN运算符,你必须在这里使用动态SQL

CREATE PROCEDURE [dbo].[usp_GetBillingSystem]
(
@BillingCode VARCHAR(300)
)
AS
BEGIN 
declare @ListOfPlanID varchar(30)
declare  @trimmed varchar(30)
declare  @replaced varchar(30)
set @ListOfPlanID =@BillingCode


If  IsNull(@ListOfPlanID,'')='' return 
If LEN(@ListOfPlanID)=0 return 
SET @trimmed=LTRIM(RTRIM(@ListOfPlanID));

set @replaced=''''+REPLACE(@trimmed,',',''',''')+'''';
declare @qry nvarchar(max);
set @qry = 'select * from BillingSystem where BillingCode IN (' + @replaced + ')';
exec sp_executesql @qry
end

答案 1 :(得分:0)

我给你一个作为替换器的函数,但它在postgresql中,所以你根据你的数据库语言修改..

CREATE OR REPLACE FUNCTION public.fn_replacer(to_rep character varying, by_rep character varying, str character varying)
 RETURNS character varying
 LANGUAGE plpgsql
AS $function$
declare
res varchar2(100);

BEGIN
    for i in 1.. length(str)
    loop
    res:= res||(case when substr(str,i,1)=TO_rep then by_rep else substr(str,i,1) end); 
    end loop;

return res;
end $function$;

答案 2 :(得分:0)

你不需要更换任何东西。如果您正在使用" IN"对于动态值,您需要动态地为自己准备查询。

通过

替换您的代码
CREATE PROCEDURE [dbo].[usp_GetBillingSystem]
(
   @BillingCode VARCHAR(300)
)
AS

BEGIN 

  exec('select * from BillingSystem where BillingCode IN ('+@BillingCode+')')

END 

肯定会有用