Replace single quotes in SQL Server

2020-01-28 04:58发布

I have this function in SQL Server to replace single quotes.

But when I insert a single quote it throws an error on Replace(@strip,''','')):

Create Function [dbo].[fn_stripsingleQuote]
    (@strStrip varchar(Max))
    returns varchar
as
begin
    declare @CleanString varchar(Max)
    SET @var=(Replace(@strip,'',''))

    return @var
end

13条回答
看我几分像从前
2楼-- · 2020-01-28 05:37

You need to double up your single quotes as follows:

REPLACE(@strip, '''', '')
查看更多
时光不老,我们不散
3楼-- · 2020-01-28 05:38

You could use char(39)

insert into my_table values('hi, my name'+char(39)+'s tim.')
查看更多
做个烂人
4楼-- · 2020-01-28 05:39

If you really must completely strip out the single quotes you can do this:

Replace(@strip, '''', '')

However, ordinarily you'd replace ' with '' and this will make SQL Server happy when querying the database. The trick with any of the built-in SQL functions (like replace) is that they too require you to double up your single quotes.

So to replace ' with '' in code you'd do this:

Replace(@strip, '''', '''''')

Of course... in some situations you can avoid having to do this entirely if you use parameters when querying the database. Say you're querying the database from a .NET application, then you'd use the SqlParameter class to feed the SqlCommand parameters for the query and all of this single quote business will be taken care of automatically. This is usually the preferred method as SQL parameters will also help prevent SQL injection attacks.

查看更多
小情绪 Triste *
5楼-- · 2020-01-28 05:40

Try escaping the single quote with a single quote:

Replace(@strip, '''', '')
查看更多
该账号已被封号
6楼-- · 2020-01-28 05:43

select replace ( colname, '''', '') AS colname FROM .[dbo].[Db Name]

查看更多
戒情不戒烟
7楼-- · 2020-01-28 05:45

Besides needing to escape the quote (by using double quotes), you've also confused the names of variables: You're using @var and @strip, instead of @CleanString and @strStrip...

查看更多
登录 后发表回答