using System; >using System.Data; >using System.Data.SqlClient; >using System.Data.SqlTypes; >using Microsoft.SqlServer.Server; >using System.Text; > >namespace CBSQLUserDefinedFunctions >{ > public partial class Transformer > { > /// <summary> > /// 9: Allow digit only > /// A: Allow letter only > /// !: Convert to uppercase > /// N: Allow Digit or Letter > /// U: Allow letter only and convert to uppercase > /// W: Allow letter only and convert to lowercase > /// X: Allow any character > /// Any other character is copied as is for display > /// </summary> > [Microsoft.SqlServer.Server.SqlFunction > (DataAccess = DataAccessKind.None, IsDeterministic = true)] > public static SqlString Transform(string value, string mask) > { > byte[] result = new byte[mask.Length]; > for (int i = 0, j = 0, k = 0; j < mask.Length; j++, k++) > { > switch (mask[j]) > { > case '9': > while (i < value.Length && !Char.IsDigit(value[i])) { i++; } > result[k] = i < value.Length ? (byte)value[i++] : (byte)'\x20'; > break; > case 'A': > while (i < value.Length && !Char.IsLetter(value[i])) { i++; } > result[k] = i < value.Length ? (byte)value[i++] : (byte)'\x20'; > break; > case 'N': > while (i < value.Length && !Char.IsLetterOrDigit(value[i])) { i++; } > result[k] = i < value.Length ? (byte)value[i++] : (byte)'\x20'; > break; > case 'U': > while (i < value.Length && !Char.IsLetter(value[i])) { i++; } > result[k] = i < value.Length ? (byte)Char.ToUpper(value[i++]) : (byte)'\x20'; > break; > case 'W': > while (i < value.Length && !Char.IsLetter(value[i])) { i++; } > result[k] = i < value.Length ? (byte)Char.ToLower(value[i++]) : (byte)'\x20'; > break; > case '!': > result[k] = i < value.Length ? (byte)Char.ToUpper(value[i++]) : (byte)'\x20'; > break; > case 'X': > result[k] = i < value.Length ? (byte)value[i++] : (byte)'\x20'; > break; > default: > result[k] = (byte)mask[j]; > break; > } > } > return ASCIIEncoding.ASCII.GetString(result); > } > }; >}And the code needed to register and test this one in SQL server:
use myDatabase >go >CREATE ASSEMBLY [SQLMaskApplier] >FROM N'c:\myLocation\bin\Release\SQLMaskApplier.dll' >WITH PERMISSION_SET = SAFE >go >CREATE FUNCTION [dbo].[Transform](@value [nvarchar](1000), @mask [nvarchar](1000)) >RETURNS [nvarchar](1000) WITH EXECUTE AS CALLER, RETURNS NULL ON NULL INPUT >AS >EXTERNAL NAME [SQLMaskApplier].[CBSQLUserDefinedFunctions.Transformer].[Transform] >GO >select dbo.Transform('123456789','999-99-9999')>