T SQL遍历表和更新字段

时间:2018-12-12 13:46:45

标签: sql sql-server

使用MS SQL Server,我有以下SQL更新了以'tbl_Test%'开头的表。

但是,我遇到这样的情况,我可以有多个以'tbl_Test%'开头的表。我将如何修改代码,使其遍历并更新所有tbl_Test%表?目前,它仅更新第一个。

DECLARE @NSQL NVARCHAR(MAX)
DECLARE @SOURCETABLE NVARCHAR(MAX)

SELECT @SOURCETABLE = TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'tbl_Test%' AND TABLE_TYPE = 'BASE TABLE'

SET @NSQL = 'UPDATE [' + @SOURCETABLE + '] SET [WEEKSTART] = CONVERT(NVARCHAR,convert(datetime, LEFT(WEEKSTART,10), 104),112)'

--PRINT @NSQL

EXEC SP_EXECUTESQL @NSQL

2 个答案:

答案 0 :(得分:1)

我可以使用以下方法进行工作:

DECLARE @NSQL NVARCHAR(MAX)
DECLARE @SOURCETABLE NVARCHAR(MAX) 

DECLARE test_cursor CURSOR FOR 

SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'tbl_Test________________%' AND TABLE_TYPE = 'BASE TABLE'

OPEN test_cursor  
FETCH NEXT FROM test_cursor INTO @SOURCETABLE

WHILE @@FETCH_STATUS = 0  
BEGIN  

SET @NSQL = 'UPDATE [' + @SOURCETABLE + '] SET [WEEKSTART] = CONVERT(NVARCHAR,convert(datetime, LEFT(WEEKSTART,10), 104),112)'

--PRINT @NSQL

EXEC SP_EXECUTESQL @NSQL

FETCH NEXT FROM test_cursor INTO @SOURCETABLE


END 

CLOSE test_cursor  
DEALLOCATE test_cursor

答案 1 :(得分:0)

我认为您需要这样的东西:

DECLARE @NSQL NVARCHAR(MAX)=''

SELECT
    @NSQL = @NSQL+CHAR(13)+'UPDATE '+INFORMATION_SCHEMA.TABLES.TABLE_NAME+' SET [WEEKSTART] = CONVERT(NVARCHAR,convert(datetime, LEFT(WEEKSTART,10), 104),112);'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE 'tbl_Test________________%'
AND TABLE_TYPE = 'BASE TABLE'

PRINT(@NSQL)
EXEC SP_EXECUTESQL @NSQL