I have written a query to find all tables from information schema and replace http by https from columns.But for text type column my query is not working.Below is the script written for it.
It is not working even it is converted to varchar
DECLARE @DatabaseName NVARCHAR(255) = 'LOTSONLINE';
DECLARE @TableName NVARCHAR(255);
DECLARE @ColumnName NVARCHAR(255);
DECLARE @Sql NVARCHAR(MAX);
-- Create a cursor to loop through tables and columns
DECLARE tableCursor CURSOR FOR
SELECT
t.TABLE_NAME AS TableName,
c.COLUMN_NAME AS ColumnName
FROM INFORMATION_SCHEMA.TABLES t
JOIN INFORMATION_SCHEMA.COLUMNS c ON t.TABLE_NAME = c.TABLE_NAME
WHERE EXISTS (
SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS AS c2
WHERE c2.TABLE_NAME = t.TABLE_NAME
--AND c2.DATA_TYPE IN ('varchar', 'nvarchar')
)
AND t.TABLE_TYPE = 'BASE TABLE' AND COLUMNPROPERTY(object_id(t.TABLE_SCHEMA+'.'+t.TABLE_NAME), c.COLUMN_NAME, 'IsIdentity')=0
AND c.DATA_TYPE IN('varchar', 'nvarchar','text','ntext');
-- Open the cursor
OPEN tableCursor;
-- Loop through tables and columns
FETCH NEXT FROM tableCursor INTO @TableName, @ColumnName;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @Sql = '
DECLARE @StartTime DATETIME = GETDATE();
DECLARE @ErrorMessage NVARCHAR(MAX);
DECLARE @FailedRowNumber INT;
BEGIN TRY
UPDATE ' + QUOTENAME(@TableName) + '
SET ' + QUOTENAME(@ColumnName) + ' = REPLACE('+CONVERT(NVARCHAR(MAX), QUOTENAME(@ColumnName) )+ ', ''http://'', ''https://'');
SET @FailedRowNumber = 0;
END TRY
BEGIN CATCH
SET @ErrorMessage = ERROR_MESSAGE();
SET @FailedRowNumber = ERROR_LINE();
END CATCH;
DECLARE @EndTime DATETIME = GETDATE();
';
--select @Sql
--return
-- Execute dynamic SQL
--EXEC sp_executesql @Sql;
FETCH NEXT FROM tableCursor INTO @TableName, @ColumnName;
END;
-- Close and deallocate the cursor
CLOSE tableCursor;
DEALLOCATE tableCursor;
1条答案
按热度按时间fdx2calv1#
You seem to have a typo:
Should be:
In other words: you need to put that
CONVERT
inside the dynamic SQL.sys
rather thanINFORMATION_SCHEMA
which is for compatibility only and can be unreliable.EXISTS
doesm't make any sense, so I've removed it. Likewise, a text column can't be anidentity
so you don't need to check for it.UPDATE
statement.STRING_AGG
.WHERE
so you are not updating all rows.