Wednesday, May 26, 2010

Controlling SQL Server 2005 behavior by setting database options regarding NULL values


To access SQL Server there are many Tools and interfaces available, these interfaces can have some default settings to control the database behavior from front end. Right now I am going to talk about most familiar database front end interface SQL Server Management Studio.

To open database Options,

Right Click your database >> Properties >> Options, you will get below screen shot.






ANSI NULL Default:

The default option ANSI NULL DEFAULT corresponds to two session settings ANSI_NULL_DFLT_ON and ANSI_NULL_DFLT_OFF. When ANSI null default database option is false, then the new columns created with the ALTER TABLE and CREATE TABLE statements are by default NOT NULL if Nullability for the column is not explicitly defined.

When this option is set to ON, columns comply with the ANSI SQL-92 rules for column nullability. That is if you don't specifically indicate whether a column in a table allows NULL values, NULLs are allowed. When this option is set to OFF, newly created columns do not allow NULLs if no nullability constrains is specified.

ANSI_NULLS:

Database option ANSI Nulls corresponds to the session settings SET ANSI_NULLS. When this option is set to true, all comparison to a null value evaluate to false. When it is set to false, comparison of non-Unicode values to a null evaluate to true if both values are NULL.

In addition if this option is set to true then your code must use the function IS NULL to determine whether a column has a NULL value. When this option is set to false, SQL Server allows=NULL as a synonym for IS NULL and <> NULL as a synonym for IS NOT NULL.

Below is the code snippet to demonstrate this behavior.

I have a user table in which Email column is having NULL values,

-- This query returns all the rows where email = null, so column to null comparison works

set
ANSI_NULLS
OFF

GO

select
*
from Users where email =
NULL


 

-- This query doesnt return any row, colum to NULL comparison doesnt work

set
ANSI_NULLS
ON

GO

select
*
from Users where email =
NULL


 

ANSI_PADDING:

When this option is set to ON, string being compared with each other are set to the same length before the comparison take place. When this option is OFF, no padding takes place.

ANSI_WARNING:

When this option is set to ON, errors or warnings are issued when conditions such as division by zero or arithmetic overflow occurs.

CONCAT_NULL_YEILDS_NULL:

When this option is set to ON, concatenating two strings results in a NULL string if either of the string is NULL. When this option is set to OFF, a NULL string treated as an empty (zero-length) string for the purpose of concatenation.

Monday, May 17, 2010

Saving changes is not permitted. How to save the changes in table design, column ordering in SQL Server 2005 / 2008


Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that requires the table to be re-created.

Screen shot:





While designing database or during initial development mode I keep changing the database schema (sometimes adding more fields or re-arranging the column positions) I got this popup many times and that makes me to go and write alter script to do the changes in table schema but through alter script I dont know how to change the column position so at last I have to fix this popup and do my changes easily through table designer.

Below are few steps to fix this popup and it will never appear

Step1: in SSMS, go to Tools>>Options…






Step 2: Drill down to Designers >> Table and Database Designers

Step 3: You will see bunch of check boxes there is one which is highlighted in above screen shot "Prevent saving changes that requires table re-creation" uncheck this check box,

Hit OK, that's all you are done, now go to your table designer and add columns, rearrange column position now it will not prompt any popup.

Cheers!!!!

Thursday, May 13, 2010

Table Variable Vs Temp table in SQL Server


In many scenarios we need some temporary table for the processing of data. Now you have two option 1) Table Variable, 2) temp Table. Which one do you choose? Let's talk about differences between these two and make sure our decision to use one of them is best for our requirement.

Table VariableTemp Table
Performance differences
Table variables don't participate in transactions, logging or locking. This means they're faster as they don't require the overhead, but conversely you don't get those features.Temporary Tables are real tables so you can do things like CREATE Indexes, etc. If you have large amounts of data for which accessing by index will be faster than temporary tables are a good option
You can pass table variables back from functions, enabling you to encapsulate and reuse logic much easier (e.g. make a function to split a string into a table of values on some arbitrary delimiter).You can create a temp table using SELECT INTO, which can be quicker to write (good for ad-hoc querying) and may allow you to deal with changing data types over time, since you don't need to define your temp table structure upfront.
A table variable can only have a primary index, A temp table can have indexes
If speed is an issue Table variables can be fasterBut if there are a lot of records, or the need to search the temp table of a clustered index, then a Temp Table would be better.
A table variables don't have column statistics, This means that the query optimizer doesn't know how many rows are in the table variable (it guesses 1), which can lead to highly non-optimal plans been generated if the table variable actually has a large number of rowsWhereas temp tables do have column statistics so the query optimizer can choose different plans for data involving temp tables
You cannot alter a Table variable with DDL statement (so you cannot create a non clustered index on a table variable). That makes every table variable a heap, or at best a table with a single, clustered index, and every table variable access a table scan (or clustered index scan)Temp tables can be altered with DDL statements
User table variable if there less records for processingUse temp table if you have huge record for processing
Syntactical difference
-To create table variable
declare @T table  
(firstColumn varchar(100))


-insert operation
insert into @T select 'some value'

-select statement
select * from @T
-You can create temp table
create table #T 
 (firstColumn varchar(100))

-Insert Operation
insert into #T select 'some value'



-Select statement
select * from #T

 

So now I think you can make wise decision which one to use when. Have fun -J


 

Happy Coding!!!

Tuesday, May 11, 2010

Script for Setting Database Mail and Sending Email From SQL Server 2008


Step1: First of all you need to enable and setup Data mail profile and account. Below is the script just copy and paste to your SQL Server query window and change the parameters accordingly.


/*

    Run this script after setting proper configurations

*/



-- ENABLE DATABASE MAIL FEATURE IN SYSTEM CONFIGURATION

use
master

go

sp_configure
'show advanced options',1

go

reconfigure
with
override

go

sp_configure
'Database Mail XPs',1

go

reconfigure

go



-- DECLARE DATABASE MAIL ACCOUNT PARAMETERS

Declare @qmail_account_name as
varchar(64);

Declare @qmail_account_description as
varchar(64);

Declare @qmail_account_email_address as
varchar(64);

Declare @qmail_account_display_name as
varchar(64);

Declare @qmail_account_username as
varchar(64);

Declare @qmail_account_password as
varchar(64);

Declare @qmail_account_mailserver_name as
varchar(64);



-- DECLARE PROFILE PARAMETERS

declare @qmail_profile_profile_name as
varchar(64);

declare @qmail_profile_description as
varchar(64);



-- DECLARE PRINCIPLES

declare @qprincipal_name as
varchar(16);



-- SET SMTP ACCOUNT DETAILS, USERNAME AND PASSWORD HERE

set @qmail_account_mailserver_name =
'smtp.bizmail.yahoo.com'
-- your smtp address

set @qmail_account_username='something@something.com'
-- username

set @qmail_account_email_address =
'myEmailName@something.com'
-- email address

set @qmail_account_password='password for user (something@something.com)'
-- password for username





set @qmail_account_name =
'YourAccountName (e.g MyAppName_EmailAccount)'

set @qmail_account_description =
'Mail account for administrative e-mail.'

set @qmail_account_display_name =
'MyApplicationName Automated Mailer'



-- PROFILE PARAMETERS ASSIGNMENT

set @qmail_profile_profile_name =
'MyAppNameEmailServiceProfile'

set @qmail_profile_description =
'Profile used for database mail jobs'



--PROFILE TYPE

set @qprincipal_name=
'public'

if ( @qmail_account_mailserver_name =
''
or @qmail_account_username=''
or @qmail_account_email_address =
''
or @qmail_account_password=''
)

begin

        Select
'Please enter SMTP details'
as [Comments]

end

else

Begin

            if
exists(select
*
from msdb.dbo.sysmail_account where [name]=@qmail_account_name)

            begin

            exec msdb.dbo.sysmail_delete_account_sp
@account_name = @qmail_account_name

            end



            EXECUTE msdb.dbo.sysmail_add_account_sp

             @account_name = @qmail_account_name,

                @description = @qmail_account_description,

                @email_address = @qmail_account_email_address,

                @display_name = @qmail_account_display_name,

                @username=@qmail_account_username,

                @password=@qmail_account_password,

                @mailserver_name = @qmail_account_mailserver_name



            if
exists(select
*
from msdb.dbo.sysmail_profile where [name]=@qmail_profile_profile_name)

            begin

            exec msdb.dbo.sysmail_delete_profile_sp
@profile_name = @qmail_profile_profile_name

            end



            EXECUTE msdb.dbo.sysmail_add_profile_sp

                 @profile_name = @qmail_profile_profile_name,

                 @description = @qmail_profile_description



            EXECUTE msdb.dbo.sysmail_add_profileaccount_sp

                @profile_name = @qmail_profile_profile_name,

                @account_name = @qmail_account_name,

                @sequence_number = 1



            EXECUTE msdb.dbo.sysmail_add_principalprofile_sp

                @profile_name = @qmail_profile_profile_name,

                @principal_name = @qprincipal_name,

                @is_default = 1 ;

end


 

 

 
Step2: Create a Sproc which will send email notification. Below is the script for that only you need to change your email To/CC, Subject, Body from your application tables or you can set anything you want. Please make sure Email profile name is proper it should be same as you have configured during Database Email Setup.


if
exists
(select 1 from
sys.objects
where name =
'p_SendEmailNotification'
and
type
=
'p')

drop
procedure p_SendEmailNotification

go



Create
Procedure [dbo].[p_SendEmailNotification]

as

Begin

Declare @ErrorCode as
int

BEGIN
TRANSACTION

declare @MailPriority varchar(8);

declare @sendAddressTo varchar (256);

declare @sendAddressCC varchar(256);

declare @MailBodyFormat varchar(8);

declare @DBMailProfile varchar(32);



set @MailBodyFormat ='HTML'

set @DBMailProfile =
'Email Profile Name which you have created during DB Mail setup (e.g MyAppNameEmailServiceProfile)'

set @MailPriority =
'Normal'



select @sendAddressTo =
'someone@someone.com,abc@abc.com'



select @sendAddressCC ='someone@someone.com,xyz@xyz.com'



EXEC msdb.dbo.sp_send_dbmail

                @profile_name = @DBMailProfile,

                @recipients=@sendAddressTo,

                @copy_recipients = @sendAddressCC,

                @importance = @MailPriority,

                @subject =
'Email Subject',

                @body =
'Email Body....hi this is test email',

                @body_format = @MailBodyFormat ;

               


set @ErrorCode =
@@ERROR


if(@ErrorCode <> 0)


begin


goto ERR_HANDLER


end




COMMIT
TRANSACTION

Set @ErrorCode =
@@Error

if @ErrorCode<>0 begin
goto ERR_HANDLER end



ERR_HANDLER:

if @ErrorCode<>0

Begin


ROLLBACK
TRANSACTION

End

End
You are done, now if you just need to call this sproc and this will send the email, if you want to Automate this email as some alert then better you create a job and within that job call this sproc as per your needed schedule.