Stored procedure for removing quotes

I am trying to write a stored procedure that will remove leading and trailing quotes from an arbitrary table and column. I keep getting an error saying the table name is not declared.

Here is SP

create table [dbo].[test] (id nvarchar(20))
insert into dbo.test values ('"07617966004766"')
go

CREATE PROCEDURE sp_stripDoubleQuotes 
    @tableName sysname,
    @columnName sysname
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE @tableName
    SET @columnName = SUBSTRING(@columnName, 2, LEN(@columnName))
    WHERE LEFT(@columnName, 1) = '"'

    UPDATE @tableName
    SET @columnName = SUBSTRING(@columnName, 1, LEN(@columnName)-1)
    WHERE RIGHT(@columnName, 1) = '"'

END
GO
exec [dbo].[sp_stripDoubleQuotes] N'[dbo].[test]', N'[id]'



select * from test

Here is the link to the violin: link to the violin

+6
source share
2 answers
CREATE PROCEDURE sp_stripDoubleQuotes 
    @tableName sysname,
    @columnName sysname,
    @SQL varchar(MAX)
AS
BEGIN
    SET NOCOUNT ON;    
    SET @SQL =

    'UPDATE ' + '[' + @tableName +']' +
    'SET' + '[' + @columnName +']' +'= SUBSTRING(' +'[' + @columnName +']' +', 2, LEN(' +'[' + @columnName +']' +'))
    WHERE LEFT('  + '[' + @columnName +']' +', 1) = '+'''"'''
    --PRINT(@SQL)
    EXEC (@SQL)

    SET @SQL =
    'UPDATE ' + '[' + @tableName +']' +
    'SET' + '[' + @columnName +']' +'= SUBSTRING(' + '[' + @columnName +']' +', 1, LEN(' + '[' + @columnName + ']' +')-1)
    WHERE RIGHT(' + '[' + @columnName +']' +', 1) = '+'''"'''
    --PRINT(@SQL)
    EXEC (@SQL)
END
GO
exec [dbo].[sp_stripDoubleQuotes] N'test', N'id'  -- exec [dbo].[sp_stripDoubleQuotes] N'[dbo].[test]', N'[id]' 

Updated 2nd: I added []to wrap the table and column if there are spaces in your table and column name. Thanks @Sean Lange and @Richard

3rd: @[benjamin moskovits] (xD), , exec [dbo].[sp_stripDoubleQuotes] N'test', N'id'. print, , .

+6
CREATE PROCEDURE sp_stripDoubleQuotes 
    @tableName sysname,
    @columnName sysname
AS
BEGIN
    SET NOCOUNT ON;
    declare @QuerytoExecute varchar(1000) 
    set @QuerytoExecute="UPDATE "+@tableName+"
    SET "+@columnName+" = SUBSTRING("+@columnName+", 2, LEN("+@columnName+"))
    WHERE LEFT("+@columnName+", 1) = '""'";
    exec (@QuerytoExecute);
    set @QuerytoExecute="
    UPDATE "+@tableName+"
    SET "+@columnName+" = SUBSTRING("+@columnName+", 1, LEN("+@columnName+")-1)
    WHERE RIGHT("+@columnName+", 1) = '""'";
    exec (@QuerytoExecute);
END
GO
0

Source: https://habr.com/ru/post/1016393/


All Articles