批量更新数据库中某字段的数值

CREATE PROCEDURE [dbo].[Sp_replace_field_value](@fieldName VARCHAR(90),
                                                @oldValue  VARCHAR(90),
                                                @newValue  VARCHAR(90))
AS
    DECLARE @tableName VARCHAR(100)
    DECLARE @sqlStmt VARCHAR(100)
  BEGIN
      DECLARE tablenamecursor CURSOR FOR
        SELECT col.table_name
        FROM   information_schema.columns col,
               information_schema.tables tab
        WHERE  col.table_name = tab.table_name
               AND tab.table_type = 'BASE TABLE'
               AND col.column_name = @fieldName
        ORDER  BY col.table_name
      OPEN tablenamecursor
      WHILE 1 = 1
        BEGIN
            FETCH next FROM tablenamecursor INTO @tableName
            IF @@fetch_status <> 0
              BREAK
            ELSE
              BEGIN
                  SET @sqlStmt = 'update ' + @tableName + ' set ' + @fieldName
                                 + ' = ' + @newValue + ' where ' + @fieldName +
                                 ' = ' + @oldValue
                  PRINT @sqlStmt
                  EXEC(@sqlStmt)
              END
        END
      CLOSE tablenamecursor
      DEALLOCATE tablenamecursor
  END


本文出自 “技术永无止境未来事在人为” 博客,谢绝转载!

你可能感兴趣的:(数据库,数值,批量更新)