用于删除引号的存储过程

时间:2017-04-07 14:35:25

标签: sql sql-server stored-procedures

我正在尝试编写一个存储过程,该过程将从任意表和列中删除前导和尾随引号。我一直收到一条错误,说明没有声明表名。

这是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

这是一个小提琴的链接: link to fiddle

2 个答案:

答案 0 :(得分:6)

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]' 

更新第二篇:我添加了[]来包装表和列,因为你的表和列名都有空格。谢谢@Sean Lange和@Richard

更新第3名:正如@ [benjamin moskovits](xD)所提到的,如果您使用硬编码括号,则正确的执行命令为exec [dbo].[sp_stripDoubleQuotes] N'test', N'id'。尝试添加或删除括号和print,以便在执行之前查看语法是否正确。

答案 1 :(得分:0)

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