How to get only alpha or alphanumeric characters from a string in SQL

How to get only alpha chars in SQL

Create Function [dbo].[RemoveNonAlphaCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin

    Declare @KeepValues as varchar(50)
    Set @KeepValues = '%[^a-z]%'
    While PatIndex(@KeepValues, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')

    Return @Temp
End

Call it like this:

Select dbo.RemoveNonAlphaCharacters('abc1234def5678ghi90jkl')

Capture

How to get alphanumeric characters in SQL

Create Function [dbo].[RemoveNonAlphaNumCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin

    Declare @KeepValues as varchar(50)
    Set @KeepValues = '%[^a-z0-9]%'
    While PatIndex(@KeepValues, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')

    Return @Temp
End

Call it like this:

Select dbo.RemoveNonAlphaNumCharacters('abc1234def5678ghi90jkl')

Capture

Select dbo.RemoveNonAlphaNumCharacters('ab£2+2(")£c123£%"&--4def567&£%"(8ghi90jkl')

Capture

SQL Function to identify invalid email addresses in the database

When you are manipulating large quantities of data, you might have some records containing email addresses which slip through as invalid.

Following function checks these conditions:

No embedded spaces
‘@’ can’t be the first character of an email address
‘.’ can’t be the last character of an email address
There must be a ‘.’ somewhere after ‘@’
the ‘@’ sign is allowed
Domain name should end with at least 2 character extension
can’t have patterns like ‘.@’ and ‘..’

--print dbo.fnc_IsValidEmail('aaa@aaa.com')
--print dbo.fnc_isValidEmail('Mi email@test.com')
CREATE FUNCTION fnc_IsValidEmail
(@Email_Address varchar(255))
RETURNS BIT
BEGIN
DECLARE @Valid bit
SET @Valid = 0
if @Email_Address=''
SET @Valid = 1
ELSE

IF (
CHARINDEX(' ',LTRIM(RTRIM(@email_address))) = 0
AND LEFT(LTRIM(@email_address),1) <> '@'
AND RIGHT(RTRIM(@email_address),1) <> '.'
AND CHARINDEX('.',@email_address ,CHARINDEX('@',@email_address)) - CHARINDEX('@',@email_address ) > 1
AND LEN(LTRIM(RTRIM(@email_address ))) - LEN(REPLACE(LTRIM(RTRIM(@email_address)),'@','')) = 1
AND CHARINDEX('.',REVERSE(LTRIM(RTRIM(@email_address)))) >= 3
AND (CHARINDEX('.@',@email_address ) = 0 AND CHARINDEX('..',@email_address ) = 0)
)
SET @Valid = 1

RETURN @Valid
END

How to call:

SELECT Email, dbo.fnc_IsValidEmail(Email) as Valid
from tblSuppliers
WHERE Email”

Capture

How to trim leading zeroes in a column/string in SQL

If you have been using this:

SUBSTRING(str_col, PATINDEX('%[^0]%', str_col), LEN(str_col))

to get your zeroes removed from a string, you might be interested in a variation that only removes the leading zeroes. The T-SQL Function has been created to be called from either Stored Procedure code or Triggers.

--print dbo.ufn_TrimLeadingZeros ('0100 ATN652')
ALTER FUNCTION [dbo].[ufn_TrimLeadingZeros] ( @Input VARCHAR(50) )
RETURNS VARCHAR(50)
AS
BEGIN
    --RETURN REPLACE(LTRIM(REPLACE(@Input, '0', ' ')), ' ', '0')
    RETURN SUBSTRING(@Input, PATINDEX('%[^0]%', @Input+'.'), LEN(@Input))
END

How to restore all SQL Server database backups from a folder

Sometimes, as a DBA, you will need to restore in bulk hundreds of databases from a server backup to another server.
To do this easily, we created this script that will back up all databases.

This is the “Restore” script at the other end.


CREATE PROCEDURE Restorealldbs

AS

SET nocount ON
— 1 – Variable declaration 
DECLARE @dbName SYSNAME
DECLARE @backupPath NVARCHAR(500)
DECLARE @cmd NVARCHAR(500)
DECLARE @fileList TABLE
(
backupfile NVARCHAR(255)
)

DECLARE @lastFullBackup NVARCHAR(500)

DECLARE @lastDiffBackup NVARCHAR(500)

DECLARE @backupFile NVARCHAR(500)

DECLARE @FileListTbl TABLE

(
logicalname          NVARCHAR(128) NOT NULL,
physicalname         NVARCHAR(260) NOT NULL,
type                 CHAR(1) NOT NULL,
filegroupname        NVARCHAR(120) NULL,
size                 NUMERIC(20, 0) NOT NULL,
maxsize              NUMERIC(20, 0) NOT NULL,
fileid               BIGINT NULL,
createlsn            NUMERIC(25, 0) NULL,
droplsn              NUMERIC(25, 0) NULL,
uniqueid             UNIQUEIDENTIFIER NULL,
readonlylsn          NUMERIC(25, 0) NULL,
readwritelsn         NUMERIC(25, 0) NULL,
backupsizeinbytes    BIGINT NULL,
sourceblocksize      INT NULL,
filegroupid          INT NULL,
loggroupguid         UNIQUEIDENTIFIER NULL,
differentialbaselsn  NUMERIC(25, 0) NULL,
differentialbaseguid UNIQUEIDENTIFIER NULL,
isreadonly           BIT NULL,
ispresent            BIT NULL,
tdethumbprint        VARBINARY(32) NULL
);

— 2 – Initialize variables 

SET @dbName = 

SET @backupPath = ‘D:SQLBackup20150306’

— 3 – get list of files 

SET @cmd = ‘DIR /b ‘ + @backupPath

INSERT INTO @fileList

(backupfile)

EXEC master.sys.Xp_cmdshell

@cmd

DECLARE @SQL NVARCHAR(1500)

DECLARE @BiGSQL NVARCHAR(max)

SET @BiGSQL=

DECLARE db_cursor CURSOR FOR
SELECT backupfile
FROM   @fileList
OPEN db_cursor

FETCH next FROM db_cursor INTO @dbName

WHILE @@FETCH_STATUS = 0

BEGIN

DECLARE @file NVARCHAR(255)

DECLARE @RestoreStatement NVARCHAR(max)

SET @BackupFile = @backupPath + @dbName

SET @RestoreStatement = N’RESTORE FILELISTONLY  FROM DISK=N”’ + @BackupFile + ””

DELETE FROM @FileListTbl
INSERT INTO @FileListTbl
EXEC(@RestoreStatement);

DECLARE @logical_data NVARCHAR(max),

@logical_log  NVARCHAR(max);

SET @logical_data = (SELECT logicalname FROM   @FileListTbl WHERE  type = ‘D’ AND fileid = 1)

SET @logical_log = (SELECT logicalname FROM   @FileListTbl WHERE  type = ‘L’ AND fileid = 2)

SET @dbName = Replace(@DbName, ‘.BAK’, )

SET @sql = N’RESTORE database ‘ + @dbName + ‘ from disk =N”’ + @BackupFile + ”’ with ‘;

SET @sql = @sql + N’ move ”’ + @logical_data + N”’ to ”D:SQL Databases’ + @logical_data + ‘.mdf” ,’ 

SET @sql = @sql + N’ move ”’ + @logical_log + N”’ to ”D:SQL Databases’ + @logical_log + ‘.ldf”  ‘

IF Isnull(@SQL, ) <> 

SET @BiGSQL = @BiGSQL + 
 + @SQL

FETCH next FROM db_cursor INTO @dbName

END

CLOSE db_cursor
DEALLOCATE db_cursor
PRINT @BiGSQL
EXEC Sp_executesql @BiGSQL

Looking for the SagePayTransaction table for nopCommerce?

0002619

Look no further.

CREATE TABLE [dbo].[SagePayServerTransaction](
[Id] [int] IDENTITY(1,1) NOT NULL,
[VPSTxId] [nvarchar](max) NULL,
[SecurityKey] [nvarchar](max) NULL,
[NotificationResponse] [nvarchar](max) NULL,
[VendorTxCode] [nvarchar](max) NULL,
[VPSSignature] [nvarchar](max) NULL,
[Status] [nvarchar](max) NULL,
[StatusDetail] [nvarchar](max) NULL,
[TxAuthNo] [nvarchar](max) NULL,
[AVSCV2] [nvarchar](max) NULL,
[AddressResult] [nvarchar](max) NULL,
[PostCodeResult] [nvarchar](max) NULL,
[CV2Result] [nvarchar](max) NULL,
[GiftAid] [nvarchar](max) NULL,
[ThreeDSecureStatus] [nvarchar](max) NULL,
[CAVV] [nvarchar](max) NULL,
[AddressStatus] [nvarchar](max) NULL,
[PayerStatus] [nvarchar](max) NULL,
[CardType] [nvarchar](max) NULL,
[Last4Digits] [nvarchar](max) NULL,
[CreatedOnUtc] [datetime] NOT NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

Encrypting Databases with Transparent Data Encryption

Quantum-Encryption-640x353 Transparent Data Encryption (TDE) enables you to encrypt an entire database.
TDE protects the database against unauthorized third parties gaining access to the hard disks or backups on which the database is stored. TDE encrypts the database by using a Database Encryption Key (DEK) that is stored in the database boot record.
The DEK is in turn protected by the database master key, which is in turn protected by the service master key. You can use BitLocker Drive Encryption, a full-volume encryption method supported by Windows Server 2008 and Windows Server 2008 R2, although this will not ensure that database backups are encrypted.

NOTE TDE AND TEMPDB
If any database on the instance uses TDE, the tempdb system database will also be encrypted.
To use TDE to encrypt a database, you must perform the following steps:

1. Create the master encryption key.

2. Create the certificate protected by the master key.

3. Create a DEK and protect it by using the certificate.

4. Encrypt the database.

The first step in deploying TDE involves creating a master encryption key. You do this by using the CREATE MASTER KEY ENCRYPTION BY PASSWORD statement. For example, you can accomplish that by using the following query:

USE master;
GO CREATE
MASTER KEY ENCRYPTION BY PASSWORD = ”;
GO

After you have created the master encryption key, the next step involves creating the certificate that will be used to encrypt the database. You can accomplish this by using the CREATE CERTIFICATE statement. For example, to create a certificate named ServerCertificate that uses the subject name Server Certificate, use the following query:

CREATE CERTIFICATE ServerCertificate WITH SUBJECT = ‘Server Certificate’;
GO

When the master key and certificate are in place, you can create the DEK for the specific database. You do this by using the CREATE DATABASE ENCRYPTION KEY statement. For example, the following query creates a DEK for the AdventureWorks2012 database:

USE AdventureWorks2012;
GO
CREATE DATABASE ENCRYPTION KEY WITH ALGORITHM = AES_128
ENCRYPTION BY SERVER CERTIFICATE ServerCertificate;
GO

After all the appropriate keys and certificates are in place, you can encrypt the database by using the ALTER DATABASE statement. For example, to encrypt the AdventureWorks2012 database, use the following query:

ALTER DATABASE AdventureWorks2012
SET ENCRYPTION ON;
GO

When using TDE, you should create a backup of the server certificate in the master database. If you lose the database server without backing this up, you cannot access data in a database protected by TDE. You can use the BACKUP CERTIFICATE statement to cre- ate a backup of the certificate and private key, both of which are required for certificate recovery. The private key password does not have to be the same as the database master key password. For example, the following code, when run from the master system database, creates a backup of the ServerCertificate certificate to a file called ServerCertExport and a PrivateKeyFile private key:

BACKUP CERTIFICATE ServerCertificate
TO FILE = ‘ServerCertExport’
WITH PRIVATE KEY (
FILE = ‘PrivateKeyFile’,
ENCRYPTION BY PASSWORD = ” );
GO

SQL Server will write these backup files to the MSSQLDATA directory of the instance.