SELECT 'alter table ' + TABLE_NAME + ' alter column ' + COLUMN_NAME + ' ' + data_type + '(' + CAST(CHARACTER_MAXIMUM_LENGTH as VARCHAR(5)) + ') NULL'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE IS_NULLABLE = 'NO'
AND DATA_TYPE IN ('VARCHAR','CHAR')
Monday, 19 June 2006
SQL : Make all columns NULLable
Saturday, 17 June 2006
Dynamic SQL - Passing a parameter using sp_execute
/*
Dynamic SQL : Passing a parameter to sp_execute
Example uses AdventureWorks db
*/
exec sp_executesql N'SELECT
e.[EmployeeID]
,c.[Title]
,c.[FirstName]
,c.[MiddleName]
,c.[LastName]
,c.[Suffix]
,e.[Title] AS [JobTitle]
,c.[Phone]
,c.[EmailAddress]
,c.[EmailPromotion]
,a.[AddressLine1]
,a.[AddressLine2]
,a.[City]
,sp.[Name] AS [StateProvinceName]
,a.[PostalCode]
,cr.[Name] AS [CountryRegionName]
,c.[AdditionalContactInfo]
FROM
[HumanResources].[Employee] e
INNER JOIN [Person].[Contact] c
ON c.[ContactID] = e.[ContactID]
INNER JOIN [HumanResources].[EmployeeAddress] ea
ON e.[EmployeeID] = ea.[EmployeeID]
INNER JOIN [Person].[Address] a
ON ea.[AddressID] = a.[AddressID]
INNER JOIN [Person].[StateProvince] sp
ON sp.[StateProvinceID] = a.[StateProvinceID]
INNER JOIN [Person].[CountryRegion] cr
ON cr.[CountryRegionCode] = sp.[CountryRegionCode]
AND cr.[Name] = @Region',N'@Region varchar(20)','Germany'
Thursday, 15 June 2006
Send email from TSQL
SQL 2005 Database Mail, Sending email from TSQL -
This script assumes you have set up database mail with an account name of 'SQL Administrator' and provided valid SMTP details.
This script assumes you have set up database mail with an account name of 'SQL Administrator' and provided valid SMTP details.
-- declare variables DECLARE @chvFrom VARCHAR(255) DECLARE @chvTo VARCHAR(255) DECLARE @chvSubject VARCHAR(255) DECLARE @chvBody VARCHAR(8000) -- set values SET @chvFrom = 'SQLAdmin@mydomain.net' SET @chvTo = 'recipient@mydomain.net' SET @chvSubject = 'Test email from ' + @@SERVERNAME SET @chvBody = 'test body text' -- send the mail EXEC msdb.dbo.sp_send_dbmail @profile_name='SQL Administrator', @recipients=@chvTo, @body=@chvBody,@subject=@chvSubject, @importance='High'
Wednesday, 7 June 2006
ISO Image Tools
Not so long ago, I was swimming in discs. Software and OS discs each on CD, neatly filed away in multiple folders. I was beginning to rival an MSDN subscription in terms of volume when I had a sort out, binned anything that had been superceeded and consolidating the rest to DVD.
The latest updates and installers are taking the form of ISO files i.e. image files of installation media. These are the FREE tools I rate for dealing with ISO files.
Daemon Tools - Emulates an optical drive so you can use an image without burning to disc.
DoISO - Create ISO files from a given directory.
ImgBurn - Burns ISOs to disc and extracts images from discs. Especially good with 'difficult' discs. Used to be known as DVD Decrypter.
The latest updates and installers are taking the form of ISO files i.e. image files of installation media. These are the FREE tools I rate for dealing with ISO files.
Daemon Tools - Emulates an optical drive so you can use an image without burning to disc.
UPDATE May 2010
Virtual Clonedrive is better and doesn't prompt you to install lots of add-ins / extras.DoISO - Create ISO files from a given directory.
ImgBurn - Burns ISOs to disc and extracts images from discs. Especially good with 'difficult' discs. Used to be known as DVD Decrypter.
Sunday, 4 June 2006
SQL 2005+ - TRY CATCH Error detection
Prior to SQL 2005, errors in TSQL code had to be tested for and captured by @@ERROR.
SQL 2005 implements the TRY CATCH syntax in the same way as javascript, c++ and subsequently the .NET languages.
For example, using AdventureWorks, I purposely attempt to delete a record I shouldnt, and receive an error -
Msg 547, Level 16, State 0, Line 2
The DELETE statement conflicted with the REFERENCE constraint "FK_EmployeeAddress_Address_AddressID". The conflict occurred in database "AdventureWorks", table "HumanResources.EmployeeAddress", column 'AddressID'.
The statement has been terminated.
@@ERROR only contains the error in the very next statement after the error, hence to both examine & display the value I have to assign it to a local variable -
TSQL Programming to catch the error -
Msg 547, Level 16, State 0, Line 2
The DELETE statement conflicted with the REFERENCE constraint "FK_EmployeeAddress_Address_AddressID". The conflict occurred in database "AdventureWorks", table "HumanResources.EmployeeAddress", column 'AddressID'.
The statement has been terminated.
Error 547 : Could not Delete record
Note : both the SQL Error and my message are returned.
Using TRY/CATCH however, the error can be caught and the script continues -
Much tidier, only my error message is returned -
Error 547 : Could not Delete record
SQL 2005 implements the TRY CATCH syntax in the same way as javascript, c++ and subsequently the .NET languages.
For example, using AdventureWorks, I purposely attempt to delete a record I shouldnt, and receive an error -
DELETE Person.Address WHERE AddressID = 1
Msg 547, Level 16, State 0, Line 2
The DELETE statement conflicted with the REFERENCE constraint "FK_EmployeeAddress_Address_AddressID". The conflict occurred in database "AdventureWorks", table "HumanResources.EmployeeAddress", column 'AddressID'.
The statement has been terminated.
@@ERROR only contains the error in the very next statement after the error, hence to both examine & display the value I have to assign it to a local variable -
TSQL Programming to catch the error -
DECLARE @ErrorResult INTEGER DELETE Person.Address WHERE AddressID = 1 SET @ErrorResult = @@ERROR IF @ErrorResult <>0 BEGIN PRINT 'Error ' + CAST(@ErrorResult AS VARCHAR(10)) + ' : Could not Delete record' END
Msg 547, Level 16, State 0, Line 2
The DELETE statement conflicted with the REFERENCE constraint "FK_EmployeeAddress_Address_AddressID". The conflict occurred in database "AdventureWorks", table "HumanResources.EmployeeAddress", column 'AddressID'.
The statement has been terminated.
Error 547 : Could not Delete record
Note : both the SQL Error and my message are returned.
Using TRY/CATCH however, the error can be caught and the script continues -
BEGIN TRY
-- Attempt delete of referenced record.
DELETE Person.Address WHERE AddressID = 1
END TRY
BEGIN CATCH
-- Do alternate action.
PRINT 'Could not Delete record'
END CATCH
Much tidier, only my error message is returned -
Error 547 : Could not Delete record
Friday, 2 June 2006
Accessing AD Users & Computers on a Member Server
Launch Microsoft Management Console
Start > Run > MMC [enter]
File > Add / Remove Snap-In
Click 'Add' to see available snap-ins.
Select 'Active Directory Users and Computers'
Click the 'Add', then 'Close' and finally 'OK'.
The functionality available will obviously depend on who you are logged in as.
Start > Run > MMC [enter]
File > Add / Remove Snap-In
Click 'Add' to see available snap-ins.
Select 'Active Directory Users and Computers'
Click the 'Add', then 'Close' and finally 'OK'.
The functionality available will obviously depend on who you are logged in as.
Thursday, 1 June 2006
Removing Database Backup History
The msdb database stores (amongst other things) the history of backups performed on the sql instance.
Once a backup has been archived, i.e. moved away from the location it was originally written to, there is no need to keep the record of the backup. Infact, these records build up, increasing the size of the msdb database (quickly if frequent transaction log backups are performed).
To see the date range of backup history you have, us this query -
Once a backup has been archived, i.e. moved away from the location it was originally written to, there is no need to keep the record of the backup. Infact, these records build up, increasing the size of the msdb database (quickly if frequent transaction log backups are performed).
To see the date range of backup history you have, us this query -
use msdb SELECT a.name , MIN(b.backup_finish_date) EarliestSuccessfulBackup , MAX(b.backup_finish_date) LatestSuccessfulBackup FROM master..sysdatabases a LEFT OUTER JOIN msdb..backupset b ON a.name = b.database_name GROUP BY a.name ORDER BY a.nameTo prevent this occuring, use system stored procedure sp_delete_backuphistory and pass it the date of the oldest record you want to keep.
use msdb go exec sp_delete_backuphistory '1/1/2006'If a database is removed altogether, zap it's backup history like this -
exec msdb.dbo.sp_delete_database_backuphistory 'Adventureworks'If backups are archived regularly, schedule a job to remove excess history records, like this -
-- Calculate date to be used when removing records, -- This example deletes records over a month old. DECLARE @dtOldest_date DATETIME SET @dtOldest_date = dateadd(month, -1, getdate()) EXEC msdb..sp_delete_backuphistory @dtOldest_dateNB :SQL 2005+ addresses this by providing cleanup tasks in the Maintainence Plans (if you use them).
Subscribe to:
Posts (Atom)