如何在不使用replace函数的情况下消除SQL Server动态sql中的单引号

时间:2016-05-24 10:04:56

标签: sql sql-server sql-server-2008 sql-server-2012

如何在不使用替换函数的情况下消除SQL Server动态sql中的单引号问题

前:

 DECLARE @QRY NVARCHAR(MAX)=''
SET @QRY= @QRY + 'SELECT CONCAT(LAST_NAME,'' ''+FIRST_NAME ) as FullName FROM TEST_TABLE'

2 个答案:

答案 0 :(得分:1)

请使用REPLACE尝试以下查询。如果我理解正确,这将对您有所帮助。这在SQL Server 2012中运行良好。

IF OBJECT_ID('tempdb..#TEST_TABLE') IS NOT NULL 
DROP TABLE #TEST_TABLE
CREATE TABLE #TEST_TABLE 
(
    LAST_NAME nvarchar(200) NOT NULL,
    FIRST_NAME nvarchar(200) NOT NULL
)
INSERT INTO #TEST_TABLE VALUES( 'LastNa''me', 'First''name')
EXEC ('SELECT CONCAT(REPLACE(LAST_NAME,'''''''',''''),'' ''+(REPLACE(FIRST_NAME ,'''''''',''''))) as FullName FROM #TEST_TABLE')

答案 1 :(得分:0)

如果您的名字和姓氏列中只有一个单引号,则可以尝试以下解决方案。

CREATE TABLE #Names
    (
      FirstName VARCHAR(30)
    , LastName VARCHAR(30)
    );

INSERT  INTO #Names
        ( FirstName, LastName )
VALUES  ( 'Mah''esh'  -- FirstName - varchar(30)
          , 'Panchala'  -- LastName - varchar(30)
          ),
        ( 'Mah''esh'  -- FirstName - varchar(30)
          , 'Panchal''a'  -- LastName - varchar(30)
          ),
        ( 'Mahesh'  -- FirstName - varchar(30)
          , 'Panchal''a'  -- LastName - varchar(30)
          );

SELECT  *
FROM    #Names;

DECLARE @QRY NVARCHAR(MAX)= '';

SET @QRY = 'SELECT CONCAT(FN.FirstName, '' '', FN.LastName) AS FullName FROM 
             ( SELECT   CASE WHEN PATINDEX(''%''''%'', FirstName) <> 0
                             THEN STUFF(FirstName, PATINDEX(''%''''%'', FirstName),
                                        1, '''')
                             ELSE FirstName
                        END AS FirstName
                      , CASE WHEN PATINDEX(''%''''%'', LastName) <> 0
                             THEN STUFF(LastName, PATINDEX(''%''''%'', LastName),
                                        1, '''')
                             ELSE LastName
                        END AS LastName
               FROM     #Names
             ) FN';
SELECT  @QRY;
EXECUTE (@QRY);