遍历表和列后动态清理数据

时间:2019-01-16 11:23:07

标签: sql sql-server

在将结果插入登台表之前,需要将其 清除所有空白和回车符。可惜我无法提供 样本数据,因为它是私人公司数据。所有表都有不同 NVARCHAR *类型的列

DECLARE @NAME NVARCHAR(4000) = ''
DECLARE @SQL NVARCHAR(4000);
DECLARE @CNAME NVARCHAR(4000) = ''
DECLARE @COUNT INT

--Storing all the database names with schema id = dbo
SELECT [name]
INTO #TEMP
FROM LIST.sys.tables
WHERE [schema_id] = SCHEMA_ID('dbo')

SELECT TOP 1 @NAME = [name] FROM #TEMP

--Looping through all the tables
WHILE (SELECT COUNT(*) FROM #TEMP) > 0
BEGIN 

SELECT @CNAME += '[' + A.[Name] + '],'
FROM LIST.sys.columns A
JOIN LIST.sys.tables B
ON A.[object_id] = B.[object_id]
WHERE B.[object_id] = OBJECT_ID(@NAME)
AND B.[schema_id] = 1
AND A.[name] <> 'Inserted_Date'

SET @CNAME = LEFT(@CNAME, LEN(@CNAME) - 1)

SET @SQL = '
SELECT ' + @CNAME + '
INTO #TEMP2
FROM [LIST].[dbo].[' + @NAME + ']
EXCEPT
SELECT ' + @CNAME + '
FROM [LIST].[STG].[' + @NAME + ']

--Here the cleaning needs to happen(Clean all columns from each table 
dynamically)

INSERT INTO [LIST].[STG].[' + @NAME + '] (' + @CNAME + ', [Inserted_Date])
SELECT ' + @CNAME + ', GETDATE()
FROM #TEMP2
'

EXEC(@SQL)           
SET @CNAME = ''   
SELECT TOP 1 @NAME = [name] FROM #TEMP  
DELETE FROM #TEMP WHERE @NAME = [name]
END
DROP TABLE #TEMP

1 个答案:

答案 0 :(得分:1)

您可能应该替换

INSERT INTO [LIST].[STG].[' + @NAME + '] (' + @CNAME + ', [Inserted_Date])
SELECT ' + @CNAME + ', GETDATE()
FROM #TEMP2

使用

INSERT INTO [LIST].[STG].[' + @NAME + '] (' + @CNAME + ', [Inserted_Date])
SELECT ' + REPLACE(REPLACE(REPLACE(CAST(@CNAME AS NVARCHAR(MAX)), CHAR(13), ''), CHAR(10), ''), ' ','') + ', GETDATE()
FROM #TEMP2