Skip to content

Instantly share code, notes, and snippets.

@alivarzeshi
Last active May 11, 2024 16:41
Show Gist options
  • Save alivarzeshi/255f2ec3fc1c0f6cf5fde0a09b6c1ed9 to your computer and use it in GitHub Desktop.
Save alivarzeshi/255f2ec3fc1c0f6cf5fde0a09b6c1ed9 to your computer and use it in GitHub Desktop.
The code updates textual columns in a SQL Server database to standardize specific Arabic characters across all tables.
USE [SQLdmRepository];
GO
-- Declare variables to store the names of the table and column currently being processed.
DECLARE @TableName NVARCHAR(MAX);
DECLARE @ColumnName NVARCHAR(MAX);
-- Declare a cursor to iterate over all textual columns in the database.
-- This cursor selects the name of the table and column from the system catalog views.
-- Only user tables (xtype = 'U') and specific textual column types are considered.
DECLARE TextColumnsCursor CURSOR FOR
SELECT
t.name AS TableName,
c.name AS ColumnName
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.user_type_id = ty.user_type_id
WHERE
ty.name IN ('ntext', 'text', 'nvarchar', 'varchar', 'char', 'nchar') -- Filters for text-based data types.
-- Open the cursor to begin processing.
OPEN TextColumnsCursor;
-- Fetch the first row from the cursor into the variables.
FETCH NEXT FROM TextColumnsCursor INTO @TableName, @ColumnName;
-- Loop through all rows in the cursor.
WHILE @@FETCH_STATUS = 0
BEGIN
-- Generate a dynamic SQL statement to replace specific Arabic characters in textual columns.
-- The REPLACE function is used to swap out characters.
-- This is necessary as the column names are dynamic and must be constructed into a string for execution.
DECLARE @SQL NVARCHAR(MAX) = N'UPDATE [' + @TableName + '] SET [' + @ColumnName + '] = REPLACE(REPLACE(CAST([' + @ColumnName + '] AS NVARCHAR(MAX)), NCHAR(1610), NCHAR(1740)), NCHAR(1603), NCHAR(1705))';
-- Execute the dynamic SQL.
--EXEC sp_executesql @SQL;
PRINT @sql
-- Fetch the next row from the cursor.
FETCH NEXT FROM TextColumnsCursor INTO @TableName, @ColumnName;
END;
-- Close and deallocate the cursor to free resources.
CLOSE TextColumnsCursor;
DEALLOCATE TextColumnsCursor;
@alivarzeshi
Copy link
Author

Purpose of the Code

The primary function of this code is to update textual columns in database tables by replacing certain Arabic characters with their standardized forms. Specifically, it targets columns that might contain the Arabic characters 'ي' (represented by Unicode NCHAR(1610)) and 'ك' (represented by Unicode NCHAR(1603)) and replaces them with 'ی' (NCHAR(1740)) and 'ک' (NCHAR(1705)), respectively. This kind of update is often necessary for standardizing data, especially in scenarios where text data has been collected from various input sources that may use slightly different character sets.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment