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
You need to double up your single quotes as follows:
You could use char(39)
If you really must completely strip out the single quotes you can do this:
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:
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.
Try escaping the single quote with a single quote:
select replace ( colname, '''', '') AS colname FROM .[dbo].[Db Name]
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...