我正在运行一个动态sql查询,该查询以很大的dB(1600个表)循环遍历所有表,并创建随后需要运行的查询。创建字符串后,我保存字符串并运行它。但是,字符串连接非常慢。我需要为每个表添加更多的样板代码,但是在下面的示例中,为了简化起见,我省略了样板代码。
我的问题是如何通过串联NVARCHAR来加快构建查询的过程?当我运行此查询时,添加更多的文本和参数串联会变得非常慢。目前需要30分钟以上,但CTE的执行时间为1秒。
DECLARE @UpdateColumnsSql NVARCHAR(MAX) = '';
WITH TableColumns AS
(
SELECT
QUOTENAME(OBJECT_SCHEMA_NAME(t.object_id)) +
'.' + QUOTENAME(t.name) AS TableName
,LOWER(c.name) AS ColumnName
,ty.name AS TypeName
,c.max_length AS ColLength
FROM
sys.tables AS t
INNER JOIN
sys.columns AS c
ON
t.object_id = c.object_id
INNER JOIN
sys.types AS ty
ON
c.system_type_id = ty.system_type_id
WHERE
c.name IN
( 'Company_ID', 'Facility_ID', 'Premises_ID' )
)
SELECT
@UpdateColumnsSql = @UpdateColumnsSql +
'ALTER TABLE ' + TableColumns.TableName +
' ADD [' + TableColumns.ColumnName + '_New] ' + TypeName +
'(' + CONVERT(VARCHAR(4), ColLength) + ')' + ' NULL
SET @sql =
'''' UPDATE T
SET T.[' + TableColumns.ColumnName + '_New] = S.[NewValue]
from ' + TableColumns.TableName + ' T
inner join NewIDList S
on Company = Company_ID
where T.[' + TableColumns.ColumnName + '] = S.OldValue
AND S.[OldColumnName] = ''''''''' + TableColumns.ColumnName + ''''''''' ''''
exec(@sql);
'
FROM
TableColumns;