简体   繁体   中英

Using REPLACE function to update a SQL Server table

I am using the following to update values in a SQL Server table:

UPDATE TABLE1 
SET COLUMN_A = REPLACE(COLUMN_A, ',', '')

I need to do this with multiple tables.

I am currently doing it manually one column at a time.

I would attempt to do this in SSIS using a for each loop component but I do not have access to SSIS in my current environment.

I would appreciate some guidance as to how to do this using perhaps a loop?

Thank you

I think you could do it with Dyanmic SQL, for example, you could use

SELECT * FROM INFORMATION_SCHEMA.COLUMNS

and add some conditions to find all your table names, column names.

then use dynamic sql as a loop to go tables one by one.

DROP TABLE IF EXISTS #temp

CREATE TABLE #temp ---identity column will be used to iterate
(
id INT IDENTITY,
TableName VARCHAR(20),
ColumnName VARCHAR(20)
)

INSERT INTO #temp
SELECT TABLE_NAME,COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
-- choose your own results with where conditions

DECLARE @SQL VARCHAR(MAX)
DECLARE @Count INT = 1
DECLARE @Table VARCHAR(20)
DECLARE @Column VARCHAR(20)

WHILE @COUNT <= (SELECT COUNT(*) FROM #temp) 
BEGIN
    SELECT @table = TABLENAME FROM #temp WHERE id = @Count
    SELECT @Column = COLUMNNAME FROM #temp WHERE id = @Count
    SELECT @sql = 'SELECT TOP 10 '+@column +' FROM '+ @table

    PRINT @SQL
SET @Count = @Count + 1

END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM