1

在 SQL Server 中,我试图替换CHAR(0)''但它不起作用,因为我的字段实际上是一个NVARCHAR字段,我的排序规则是,Latin1_General_CI_AS但是当我转换为SQL_Latin1_General_CP1_CI_AS它时,它只适用于VARCHAR而不是NVARCHAR

SELECT val, REPLACE(val , CHAR(0), 'x')
FROM    (
         SELECT 'a' + CHAR(0) + 'b' AS val
        ) AS X

退货a | a

SELECT val, REPLACE(CAST(val COLLATE SQL_Latin1_General_CP1_CI_AS AS varchar(100)), CHAR(0), 'x')
FROM    (
         SELECT 'a' + CHAR(0) + 'b' AS val
        ) AS X

退货a | axb

SELECT val, REPLACE(CAST(val COLLATE SQL_Latin1_General_CP1_CI_AS AS varchar(100)), CHAR(0), 'x')
FROM    (
         SELECT CAST('a' + CHAR(0) + 'b' AS NVARCHAR(100)) AS val
        ) AS X
SELECT val, REPLACE(CAST(val COLLATE SQL_Latin1_General_CP1_CI_AS AS nvarchar(100)), CHAR(0), 'x')

退货a | axb

FROM    (
         SELECT CAST('a' + CHAR(0) + 'b' AS NVARCHAR(100)) AS val
        ) AS X
SELECT val, REPLACE(CAST(val COLLATE SQL_Latin1_General_CP1_CI_AS AS varchar(100)), nCHAR(0), 'x')

退货a | a

FROM    (
         SELECT CAST('a' + CHAR(0) + 'b' AS NVARCHAR(100)) AS val
        ) AS X
SELECT val, REPLACE(CAST(val COLLATE SQL_Latin1_General_CP1_CI_AS AS nvarchar(100)), nCHAR(0), 'x')

退货a | a

FROM    (
         SELECT CAST('a' + CHAR(0) + 'b' AS NVARCHAR(100)) AS val
        ) AS X

退货a | a

有没有一种方法可以替换0x0000字符''而不丢失我的 NVARCHAR 状态

编辑:预期值为a | axb最后一个查询(或类似但支持NVARCHAR.

4

1 回答 1

2

使用二进制整理子句,无需CAST

;WITH T
     AS (SELECT CAST('a' + CHAR(0) + 'b' AS NVARCHAR(100)) AS val)
SELECT val,
       REPLACE(val COLLATE Latin1_General_100_BIN, nCHAR(0), 'x')
FROM   T 
于 2012-12-17T14:17:54.110 回答