我有一个包含三列的表:A,B和C.
A ; B; C
"a1"; "b1"; "c1"
"a2"; "b2"; "c3"
"a3"; "b3"; "c3"
我需要从表格中的所有行中删除引号。 In this post我找到了一个有效但需要指定所有列名称的解决方案:
UPDATE myTable
SET A = REPLACE(A, '"', '');
UPDATE myTable
SET B = REPLACE(B, '"', '');
UPDATE myTable
SET C = REPLACE(C, '"', '');
问题:是否有一种不那么冗长的方法将替换应用于所有列?例如一行表达式?
由于
答案 0 :(得分:3)
我没有这方面的一行脚本,但是当我将数据存入sql server时,当我将数据中的所有双引号删除后,我的代码中有几行代码。这些列是varchar数据类型。
- 摆脱数据中的双引号
Declare @ColName SYSNAME , @Sql Nvarchar(Max)
Declare Cur Cursor FOR
SELECT c.name
from sys.columns c inner join sys.tables t on c.object_id = t.object_id
Where t.name = 'myTable' --<-- Your Table name
OPEN Cur
FETCH NEXT FROM Cur INTO @ColName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = 'UPDATE myTable
SET ' + QUOTENAME(@ColName) + ' = LTRIM(RTRIM(ISNULL(REPLACE(' + QUOTENAME(@ColName) + ' , ''"'' , '''') , '''')))'
--PRINT @SQL
Exec sp_executesql @Sql
FETCH NEXT FROM Cur INTO @ColName
END
CLOSE Cur
DEALLOCATE Cur
GO
答案 1 :(得分:0)
如果记录数量不大: -
Find
和Replace All
替换为双引号。答案 2 :(得分:0)
以下程序将用任何表中的另一个单个字符替换任何单个字符:)
USE [TSQL2012]--your database name
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE dbo.replace_char
@char_to_replace char(1), --character to be replaced
@expected_char char(1),
@table_name nvarchar(128) --your table name
AS
BEGIN
--Variable declaration
DECLARE @Column_Count_1 int
DECLARE @SQLString AS NVARCHAR(4000)
DECLARE @count int=1
DECLARE @column_name nvarchar(128)
--Getting the count of column
SET @SQLString=N'select @Column_Count=count(*) from '+ @table_name
EXEC sp_executesql @SQLString
, N'@Column_Count int OUTPUT'
, @Column_Count = @Column_Count_1 OUTPUT
--Getting the actual column names into a temporary table
select c.name as name
into #temp_column_names
from sys.tables t
join sys.columns c
on t.object_id=c.object_id
where t.name=@table_name
--Looping through each column to replace the required character
WHILE (@count<=@Column_Count_1)
BEGIN
--setting the column name
SET @column_name=(select top 1 name from
(select Row_number()over (order by name) as r_n_n, name
from #temp_column_names) aa
where r_n_n >=@count)
--updating the rows
SET @SQLString =N'Update ' + @table_name
SET @SQLString= @SQLString + N' Set ' + @column_name
SET @SQLString= @SQLString + N' = replace(' + @column_name
SET @SQLString =@SQLString + N',''' +@char_to_replace
SET @SQLString=@SQLString + N''',''' +@expected_char
SET @SQLString=@SQLString + N''');'
EXEC(@SQLString);
SET @count=@count+1;
END
--Dropping the temp table
DROP TABLE #temp_column_names
END
GO
执行上述程序
EXEC dbo.replace_char @char_to_replace, @expected_char, @table_name
在你的情况下
EXEC dbo.replace_char '"', '','Sample_1'
Sample_1是我创建的表。