我正在使用AdventureWorks2008R2数据库,我试图弄清楚是否有办法遍历此数据库中的所有表,然后给出条件迭代特定列中的行那张桌子?
目前我有
SELECT DISTINCT
INFORMATION_SCHEMA.COLUMNS.ORDINAL_POSITION,TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE ('%date%') AND COLUMN_NAME Not LIKE '%JobCandidate%'
;
我想从这里做的是查看这些表格,然后根据给定条件更改日期。
在非SQL代码和松散的伪代码中,它可能类似于
FOR TABLES
SELECT A TABLE WITH A COLUMN THAT HAS A DATE IN IT
FOR COLUMN_WITH_DATE_HEADER
IF ROW HAS DATE GIVEN SOME CONDITION
UPDATE ROW IN THAT TABLE
有人可以协助吗?
提前致谢!
更新
这是我从@Mars解决方案中创建的代码。
SELECT DISTINCT
IDENTITY(int,1,1) AS SN,
INFORMATION_SCHEMA.COLUMNS.ORDINAL_POSITION
, TABLE_SCHEMA
, TABLE_NAME
, COLUMN_NAME
INTO #temptable
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE ('%date%')
AND COLUMN_NAME Not LIKE '%JobCandidate%' AND
COLUMN_NAME NOT LIKE '%BirthDate%';
DECLARE @start INT=1
, @end INT=0
, @query NVARCHAR(MAX)='';
DECLARE @conditions NVARCHAR(MAX)='' ;
SELECT @end=MAX(SN)
FROM #temptable
WHILE (@start<=@end)
BEGIN
SELECT
@conditions = ' WHERE ' + 'YEAR('+ COLUMN_NAME +')' + ' < 2009',
@query= 'UPDATE '+TABLE_SCHEMA+'.'
+TABLE_NAME +' SET '+ COLUMN_NAME
+' = dateadd(YEAR,8,' + COLUMN_NAME + ')'
FROM #temptable
WHERE SN =@start
EXEC (@query)
SET @start+=1
END
DROP TABLE #temptable
答案 0 :(得分:1)
您需要设置更新所需的日期和条件以检查变量@updatatingDate
和@conditions
SELECT DISTINCT
IDENTITY(int,1,1) AS SN,
INFORMATION_SCHEMA.COLUMNS.ORDINAL_POSITION
, TABLE_SCHEMA
, TABLE_NAME
, COLUMN_NAME
INTO #temptable
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE ('%date%')
AND COLUMN_NAME Not LIKE '%JobCandidate%';
DECLARE @start INT=1
, @end INT=0
, @query NVARCHAR(MAX)=''
, @updatatingDate NVARCHAR(100)='2017-04-04'
, @conditions NVARCHAR(MAX)='1=1'
SELECT @end=MAX(SN)
FROM #temptable
WHILE (@start<=@end)
BEGIN
SELECT
@query= 'UPDATE '+TABLE_SCHEMA+'.'
+TABLE_NAME +' SET '+ COLUMN_NAME
+' ='''+@updatatingDate+''' WHERE '
+@conditions
FROM #temptable
WHERE SN =@start
EXEC (@query)
SET @start+=1
END
--DROP TABLE #temptable;