Sunday 14 March 2010

Trigger

Triggering

Concept
Trigger that will run when someone updates the SalaryGrade within the specified table automatically the trigger will capture the previous salarygrade and insert into another table along with New and previous salarygrade..

--- Table 1 : Employee
Create Table Employee (
EmployeeID int not null
Constraint pk_Employee_EmployeeID primary key,
EmployeeName varchar(10) not null,
SalaryGrade varchar(10) not null,
Slary smallmoney not null
)
-------------------------------------------------------------
--- Table 2 : EmployeeChanges
Create Table EmployeeChanges (
ChangeID int identity(1,1) not null
Constraint pk_EmployeeChanges_ChangeID primary key,
ChangeDateTime datetime not null,
EmployeeName varchar(10) not null,
OldSalaryGrade varchar(10) not null,
NewSalaryGrade varchar(10) not null,
)
--------------------------------------------------------------
--- Before Update Insert to Another Table
CREATE Trigger tr_Update_RecordSalaryGradeChanges
On Employee
For Update As
declare @rowcount as int
declare @ChangeDateTime as datetime
declare @EmployeeName as varchar(10)
declare @OldSalaryGrade as smallmoney
declare @NewSalarygrade as smallmoney
If @@RowCount > 0
Begin
If update (Salarygrade)
Begin
begin transaction
select @ChangeDateTime = getdate(),
@EmployeeName = Inserted.EmployeeName,
@OldSalaryGrade = Deleted.Salarygrade,
@NewSalaryGrade = Inserted.Salarygrade
from Inserted inner join Deleted
on Inserted.EmployeeID = Deleted.EmployeeID
insert EmployeeChanges(ChangeDateTime, EmployeeName, OldSalaryGrade, NewSalarygrade)
values (@ChangeDateTime, @EmployeeName, @OldSalaryGrade, @NewSalarygrade)
set @rowcount = @@rowcount
if @@rowcount = 1
Begin
Commit transaction
End
Else
Begin
Rollback transaction
RaisError('Error recording to change table, contact admin', 16, 1)
End
End
End
Return
--- drop trigger tr_Update_RecordDeliveryChargeChanges
----------------------------------------------------------------

--- For Multiple Records Update in Employee Tables
Alter Trigger tr_Update_RecordSalaryGradeChanges
On Employee
For Update As

If update (salarygrade)
Begin

Insert EmployeeChanges(ChangeDateTime, EmployeeName, OldSalaryGrade, NewSalaryGrade)
Select getdate(), Inserted.EmployeeName,Deleted.SalaryGrade,Inserted.SalaryGrade
From Inserted inner join Deleted
on Inserted.EmployeeID = Deleted.EmployeeID

If @@error <> 0
Begin
RaisError('Error recording to change table, contact admin', 16, 1)
End
End
----------------------------------------------------------
--- For mail send while Update in Employee Table
/*
To ensure before this trigger configure your database mail.
for more information please visit db mail configuration Page :
http://sqlservertechnics.blogspot.com/2010/03/db-mail-configuration.html
*/
ALTER TRIGGER EmployeeUpdateMail
-- and the table is CustomerInfo
ON Employee
-- trigger is fired when an update is made for the table
FOR UPDATE
AS
-- holds the EmployeeID so we know which Customer was updated
declare @EmployeeID varchar(10)
-- holds the body of the email
declare @body varchar(2000)
-- holds the old customer name which has been changed
declare @EmployeeName varchar(10)
-- holds the new customer name
declare @EmployeeNewName varchar(10)
-- gets the previous customer first name that was deleted
SELECT @EmployeeID = EmployeeID,
@EmployeeName = d.EmployeeName
FROM deleted d
-- gets the new customer first name
SELECT @EmployeeNewName = EmployeeName
FROM inserted

SET @body = 'Employee with ID= ' + @EmployeeID + ' has been updated
with previous Employee Name is : ' + @EmployeeName + 'and the
New Employee Name is : '+ @EmployeeNewName
--- xp_sendmail is the extended sproc used to send the mail
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Database Email',
@recipients = 'adscxdasf@dsfasdf.com',
@body = @body,
@subject = 'Employee Information Updated'
GO
-----------------------------------------------------------
-- Workouts
Select * from dbo.Employee
Select * from dbo.EmployeeChanges
--- delete from dbo.EmployeeChanges

update Employee set salarygrade='FinalMail'
where EmployeeID in (1,2)

update Employee set EMPLOYEENAME='FinalMail5'
where EmployeeID in (1)
-----------------------------------------------------------

Wednesday 10 March 2010

Error and Troubleshoot

Error and Troubleshoot in SQL server 2005

-- Errors and Error methods
BEGIN TRY
-- SELECT 1/0--Evergreen divide by zero example!
select FirstName/100 from customer
END TRY

BEGIN CATCH
SELECT 'There was an error! ' + ERROR_MESSAGE()
SELECT ERROR_NUMBER()
SELECT ERROR_SEVERITY()
SELECT ERROR_STATE()
SELECT ERROR_PROCEDURE()
SELECT ERROR_LINE()
SELECT ERROR_MESSAGE()
RETURN
END CATCH;



-- Error Query

select distinct e.department_id + ' - ' +d.department_name as [Department Name]
from employee e
left outer join Department as d on d.department_id=e.department_id

/*-- Error Message
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to bigint.
*/

-- Correct Query
select distinct
CAST(e.department_id AS NVARCHAR) + ' - ' +d.department_name as [Department Name]
from employee e
left outer join Department as d on d.department_id=e.department_id







_______________________________________________________________

Thursday 4 March 2010

SQL Server Back Up and History

SQL Server Back Up and History


-- BACKUP SERVICE MASTER KEY
BACKUP SERVICE MASTER KEY TO FILE = 'C:\backup\servicemasterkey_backup.key'
ENCRYPTION BY PASSWORD = 'password@5'

-- RESTORE SERVICE MASTER KEY
RESTORE SERVICE MASTER KEY FROM FILE = 'C:\backup\servicemasterkey_backup.key'
DECRYPTION BY PASSWORD = 'password@5'
FORCE

-- BACKUP MASTER KEY
BACKUP MASTER KEY TO FILE = 'C:\backup\masterkey_backup.key'
ENCRYPTION BY PASSWORD = 'password@5'

-- RESTORE MASTER KEY
RESTORE MASTER KEY FROM FILE = 'C:\backup\masterkey_backup.key'
DECRYPTION BY PASSWORD = 'password@5'
ENCRYPTION BY PASSWORD = 'password@5'
FORCE

-- To Back up Database
BACKUP DATABASE [Employee] TO DISK = N'C:\Backup\Employee.bak'
WITH NOFORMAT, NOINIT, NAME = N'Employee-Full Database Backup',
SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO

-- To Restore Databse
RESTORE DATABASE [Employee] FROM DISK = N'C:\Backup\Employee.bak'
WITH FILE = 1,
MOVE N'Employee_log'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\Employee_log.LDF',
NOUNLOAD, REPLACE, STATS = 10
GO


--- SQL Server Script to Retrievw Job History
select job_name, run_datetime, run_duration
from
(
select job_name, run_datetime,
SUBSTRING(run_duration, 1, 2) + ':' + SUBSTRING(run_duration, 3, 2) + ':' +
SUBSTRING(run_duration, 5, 2) AS run_duration
from
(
select DISTINCT
j.name as job_name,
run_datetime = CONVERT(DATETIME, RTRIM(run_date)) +
(run_time * 9 + run_time % 10000 * 6 + run_time % 100 * 10) / 216e4,
run_duration = RIGHT('000000' + CONVERT(varchar(6), run_duration), 6)
from msdb..sysjobhistory h
inner join msdb..sysjobs j
on h.job_id = j.job_id
) t
) t
order by job_name, run_datetime

-- or

SELECT sj.name,
sja.run_requested_date,
CONVERT(VARCHAR(12), sja.stop_execution_date-sja.start_execution_date, 114) Duration
FROM msdb.dbo.sysjobactivity sja
INNER JOIN msdb.dbo.sysjobs sj
ON sja.job_id = sj.job_id
WHERE sja.run_requested_date IS NOT NULL
ORDER BY sja.run_requested_date desc


-- To Retrievw Path and Size of the Databas Backup
SELECT top 10 s.database_name,
m.physical_device_name,
s.backup_size,
cast(s.backup_size/1000000 as varchar(14))+' '+'MB' as bkSize,
CAST (DATEDIFF(second,s.backup_start_date , s.backup_finish_date)AS VARCHAR(4))+' '+'Seconds' TimeTaken,
s.backup_start_date,
CASE s.[type]
WHEN 'D' THEN 'Full'
WHEN 'I' THEN 'Differential'
WHEN 'L' THEN 'Transaction Log'
END as BackupType,
s.server_name,
s.recovery_model
FROM msdb.dbo.backupset s
inner join msdb.dbo.backupmediafamily m
ON s.media_set_id = m.media_set_id
-- Optional Condition
-- WHERE s.database_name = 'BackupReport'
-- ORDER BY database_name, backup_start_date, backup_finish_date

-- To check SQL Server FULL database backups are successful or not
SELECT database_name, backup_start_date, type, *
FROM msdb.dbo.backupset
WHERE backup_start_date BETWEEN DATEADD(hh, -24, GETDATE()) AND GETDATE()
AND Type = 'D'
ORDER BY backup_set_id DESC
GO

-- To check SQL Server Transaction Log backups are successful or not
SELECT database_name, backup_start_date, type, *
FROM msdb.dbo.backupset
WHERE backup_start_date BETWEEN DATEADD(hh, -344, GETDATE()) AND GETDATE()
AND Type = 'L'
ORDER BY backup_set_id DESC
GO

-- To check SQL Server Differential Backups are successful or not
SELECT database_name, backup_start_date, type, *
FROM msdb.dbo.backupset
WHERE backup_start_date BETWEEN DATEADD(hh, -24, GETDATE()) AND GETDATE()
AND Type = 'I'
ORDER BY backup_set_id DESC
GO

-- To check SQL Server File\File Group Backups are successful or not
SELECT database_name, backup_start_date, type, *
FROM msdb.dbo.backupset
WHERE backup_start_date BETWEEN DATEADD(hh, -24, GETDATE()) AND GETDATE()
AND Type = 'F'
ORDER BY backup_set_id DESC
GO

Wednesday 3 March 2010

Operator in SQL Server 2005

--*************************************--
-- ALL About Operator --
--*************************************--
-- ADD or Create New Operator
USE [msdb]
GO
EXEC msdb.dbo.sp_add_operator @name=N'Dbmail',
@enabled=1,
@pager_days=0,
@email_address=N'testmailfromdb@domin.com',
@pager_address=N'',
@netsend_address=N''
GO

-- UPDATE operator
USE [msdb]
GO
EXECUTE msdb.dbo.sp_update_operator @name = 'Dbmail',
@email_address = 'testmailfromdb2@domin.com'
GO

-- DELETE operator with the same name.
EXECUTE msdb.dbo.sp_delete_operator @name = N'Dbmail'

-- To DISABLE the operator
EXEC msdb.dbo.sp_update_operator @name=N'Dbmail',
@enabled=0

-- To ENABLE the operator
EXEC msdb.dbo.sp_update_operator @name=N'Dbmail',
@enabled=1

Tuesday 2 March 2010

DB Mail Configuration

Database Mail Configuration in SQL Server 2005

-- Enabling Database Mail

sp_configure 'show advanced', 1;
GO
RECONFIGURE;
GO

sp_configure 'Database Mail XPs', 1;
GO
RECONFIGURE;
GO

-- Checking Database Mail is running or not
EXEC msdb.dbo.sysmail_help_status_sp;

-- Starting Database Mail
EXEC msdb.dbo.sysmail_start_sp;

-- Stopping Database Mail
EXEC msdb.dbo.sysmail_stop_sp;

-- Checking Mail Queue Status
-- The state of mail queue should be 'RECEIVES_OCCURRING'
-- The column length gives the number of mails in the queue
EXEC msdb.dbo.sysmail_help_queue_sp @queue_type = 'mail';

-- Adding Database Mail Account
-- Add valid smtp mailserver_name
EXECUTE msdb.dbo.sysmail_add_account_sp
@account_name = 'Production Database Administration Profile',
@description = 'Administrative e-mail account',
@email_address = 'dfsafasfddffasd@yahoo.com',
@display_name = 'Automated Admin Mailer',
@mailserver_name = 'mail.yahoo.com' ;

-- Adding Database Mail Profile
EXECUTE msdb.dbo.sysmail_add_profile_sp
@profile_name = 'Production Database Administration Profile',
@description = 'Administrative mail profile' ;

-- Adding Database Mail Account to Profile
/* Add unique integer Sequence number for respective account in a profile. Mail is sent through the account based on the order of sequence number. */
EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
@profile_name = 'Production Database Administration Profile',
@account_name = 'Production Database Administration Account',
@sequence_number = 1 ;

-- Grant access to the profile
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
@profile_name = 'Production Database Administration Profile',
@principal_name = 'public',
@is_default = 1

-- Listing all Database Mail Accounts
EXECUTE msdb.dbo.sysmail_help_account_sp ;

-- Listing all Database Mail Profiles
EXECUTE msdb.dbo.sysmail_help_profile_sp;

-- Listing all Database Mail Profiles with their respective Accounts
EXECUTE msdb.dbo.sysmail_help_profileaccount_sp;

--To find out the profile name
SELECT [profile_id]
,[name]
,[description]
,[last_mod_datetime]
,[last_mod_user]
FROM [msdb].[dbo].[sysmail_profile]

-- Deleting Database Mail Account
-- Pass Account name or account id as the parameter
EXECUTE msdb.dbo.sysmail_delete_account_sp
@account_name = 'Production Database Administration Account' ;

EXECUTE msdb.dbo.sysmail_delete_account_sp
@account_id = 1;

-- Deleting Database Mail Profile
-- Pass Profile name or profile id as the parameter
EXECUTE msdb.dbo.sysmail_delete_profile_sp
@profile_name = 'Production Database Administration Profile' ;

EXECUTE msdb.dbo.sysmail_delete_profile_sp
@profile_id = 1;

-- Deleting Database Mail Account from Profile
EXECUTE msdb.dbo.sysmail_delete_profileaccount_sp
@profile_name = 'Production Database Administration Profile',
@account_name = 'Production Database Administration Account' ;

-- Updating Database Mail Account
EXECUTE msdb.dbo.sysmail_update_account_sp
@account_id = 1,
@account_name = 'DBA',
@email_address = 'dsafffffewew@yahoo.com',
@display_name = 'Admin';

-- Updating Database Mail Account
EXECUTE msdb.dbo.sysmail_update_profile_sp
@profile_id = 1,
@profile_name = 'DBA'

-- Sending Database Mail
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Production Database Administration Profile',
@recipients = 'dafskjkj@yahoo.com',
@copy_recipients = 'Abcjkdsfah@yahoo.com',
@blind_copy_recipients ='dalasldkfa@yahoo.com',
@body_format = 'TEXT',
@body = 'Test Email',
@subject = 'Automated Test Mail';

-- Send file attachments
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Production Database Administration Profile',
@recipients = 'dsafsdfasdf@yahoo.com',
@file_attachments = 'D:\File1.txt;D:\File2.txt'
@body = 'Test File Attachments',
@subject = 'Files Attached';

-- Send mail with query results
/*Specify value 0 for @attach_query_result_as_file for including the contents in body and specify value 1 to send the results as attachment*/
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Production Database Administration Profile',
@recipients = 'asdfjjhdsaf@yahoo.com',
@query = 'SELECT COUNT(*) FROM msdb.dbo.DTA_input' ,
@subject = 'Imported Records Count',
@attach_query_result_as_file = 1 ;

-- Sending HTML Mail
DECLARE @tableHTML VARCHAR(MAX) ;

SET @tableHTML =
'

HTML Mail

' +
'' +
'' +
'
Table Header
' ;

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Production Database Administration Profile',
@recipients='fsdfgdsgds@yahoo.com',
@subject = 'HTML mail',
@body = @tableHTML,
@body_format = 'HTML' ;

-- Checking Mail Delivery status
-- Delivery Status can be viewed from column sent_status
-- Check all mails AND Clear histroy or allitems
select * from msdb.dbo.sysmail_allitems order by last_mod_date desc
-- DELETE from msdb.dbo.sysmail_allitems

-- Check sent mails and clear
select * from msdb.dbo.sysmail_sentitems order by last_mod_date desc
-- DELETE from msdb.dbo.sysmail_sentitems
-- Check failed mails
select * from msdb.dbo.sysmail_faileditems order by last_mod_date desc
-- If you want to clear run this script
-- DELETE from msdb.dbo.sysmail_faileditems
-- Checking Failed Mail Reason
-- Column Description returns the Failure reason
select * from msdb.dbo.sysmail_event_log where mailitem_id ='1507'
DELETE from msdb.dbo.sysmail_event_log

-- Monitoring Database Mail run msdb DB
SELECT * FROM msdb.dbo.sysmail_allitems where recipients='dsaffsdfds@yahoo.com'
--delete FROM msdb.dbo.sysmail_allitems where recipients='dsafsadf@yahoo.com'
SELECT * FROM msdb.dbo.sysmail_event_log
SELECT * FROM msdb.dbo.sysmail_sentitems
SELECT * FROM msdb.dbo.sysmail_faileditems
SELECT * FROM msdb.dbo. sysmail_mailattachments
SELECT count(*) FROM msdb.dbo.sysmail_allitems
SELECT * FROM msdb.dbo.sysmail_sentitems
SELECT count(*) FROM msdb.dbo.sysmail_unsentitems
SELECT * FROM msdb.dbo.sysmail_unsentitems

-- Troubleshooting DB Mail --
/*
Msg 14650, Level 16, State 1, Procedure sp_send_dbmail, Line 72
Service Broker message delivery is not enabled in this database. Use the ALTER DATABASE statement to enable Service Broker message delivery.
*/
/* A value of 0 indicates that Service Broker message delivery is not activated in the msdb database */
SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb'
--- check members of the DatabaseMailUserRole
EXEC msdb.sys.sp_helprolemember 'DatabaseMailUserRole'
EXEC msdb.dbo.sysmail_help_principalprofile_sp
--- check status of Database Mail
EXECUTE msdb.dbo.sysmail_help_status_sp ;
---start Database Mail in a mail host database
EXECUTE msdb.dbo.sysmail_start_sp

EXEC msdb.dbo.sysmail_help_queue_sp @queue_type = 'mail'
-- Kill all connection to msdb database and run:
-- stop the agent service, run the query, and then restart the service.
ALTER DATABASE msdb SET ENABLE_BROKER

-- ALTER DATABASE MSDB SET NEW_BROKER

-- You can set is_broker_enabled column value to 1 by executing the following command
ALTER DATABASE Employee SET NEW_BROKER

ALTER DATABASE Employee SET ENABLE_BROKER

ALTER DATABASE Employee SET ERROR_BROKER_CONVERSATIONS

ALTER DATABASE Employee SET TRUSTWORTHY ON

ALTER DATABASE Employee SET DISABLE_BROKER


Sunday 28 February 2010

SHRINK LOG FILE

SHRINK LOG FILE in SQL Server 2005

-- To find out the Free Disk Space
xp_fixeddrives

-- Before Check the DB Size

DBCC SQLPERF(LOGSPACE)

-- Want to see the current db .mdf and .ldf file run this script
SELECT file_id, name FROM sys.database_files
-- or if you know the database name (ex: db Name : Employee)
SELECT file_id, name FROM employee.sys.database_files

--Syntax to Shrink LoG file
BACKUP LOG WITH TRUNCATE_ONLY

DBCC SHRINKFILE (, Size)
-- Size is in MB

-- Shrink LoG File Example:-

BACKUP LOG Employee WITH TRUNCATE_ONLY

DBCC SHRINKFILE (Employee_log, 500)
-- It will shrink 500 MB Size
-- Example Before Shrink your Employee DB size 1000MB
-- After Shrink your Employee DB Size would Be 500MB

-- To find the DB Size Run the following Command
DBCC SQLPERF(LOGSPACE)

--- Shrink Database
USE master;
DBCC SHRINKDATABASE (Employee, 10);
GO


-- Increase Transaction Log size
ALTER DATABASE Employee
MODIFY FILE
(NAME = Employee_log,SIZE = 80MB)

--- Trouble Shot
If Suppose you got the error message like this you need to change the log size which is higher than you previous log file size

Msg 5039, Level 16, State 1, Line 1
MODIFY FILE failed. Specified size is less than current size.

------------------------------------------------------------------------------------
-- To find out all drive space details and Free space details
SET NOCOUNT ON


IF EXISTS (SELECT name FROM tempdb..sysobjects WHERE name = '##_DriveSpace')
DROP TABLE ##_DriveSpace

IF EXISTS (SELECT name FROM tempdb..sysobjects WHERE name = '##_DriveInfo')
DROP TABLE ##_DriveInfo


DECLARE @Result INT
, @objFSO INT
, @Drv INT
, @cDrive VARCHAR(13)
, @Size VARCHAR(50)
, @Free VARCHAR(50)
, @Label varchar(10)

CREATE TABLE ##_DriveSpace
(
DriveLetter CHAR(1) not null
, FreeSpace VARCHAR(10) not null

)

CREATE TABLE ##_DriveInfo
(
DriveLetter CHAR(1)
, TotalSpace bigint
, FreeSpace bigint
, Label varchar(10)
)

INSERT INTO ##_DriveSpace
EXEC master.dbo.xp_fixeddrives


-- Iterate through drive letters.
DECLARE curDriveLetters CURSOR
FOR SELECT driveletter FROM ##_DriveSpace

DECLARE @DriveLetter char(1)
OPEN curDriveLetters

FETCH NEXT FROM curDriveLetters INTO @DriveLetter
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
BEGIN

SET @cDrive = 'GetDrive("' + @DriveLetter + '")'

EXEC @Result = sp_OACreate 'Scripting.FileSystemObject', @objFSO OUTPUT

IF @Result = 0

EXEC @Result = sp_OAMethod @objFSO, @cDrive, @Drv OUTPUT

IF @Result = 0

EXEC @Result = sp_OAGetProperty @Drv,'TotalSize', @Size OUTPUT

IF @Result = 0

EXEC @Result = sp_OAGetProperty @Drv,'FreeSpace', @Free OUTPUT

IF @Result = 0

EXEC @Result = sp_OAGetProperty @Drv,'VolumeName', @Label OUTPUT

IF @Result <> 0

EXEC sp_OADestroy @Drv
EXEC sp_OADestroy @objFSO

SET @Size = (CONVERT(BIGINT,@Size) / 1048576 )

SET @Free = (CONVERT(BIGINT,@Free) / 1048576 )

INSERT INTO ##_DriveInfo
VALUES (@DriveLetter, @Size, @Free, @Label)

END
FETCH NEXT FROM curDriveLetters INTO @DriveLetter
END

CLOSE curDriveLetters
DEALLOCATE curDriveLetters

PRINT 'Drive information for server ' + @@SERVERNAME + '.'
PRINT ''

-- Produce report.
SELECT DriveLetter
, Label
, FreeSpace AS [FreeSpace MB]
, (TotalSpace - FreeSpace) AS [UsedSpace MB]
, TotalSpace AS [TotalSpace MB]
, ((CONVERT(NUMERIC(9,0),FreeSpace) / CONVERT(NUMERIC(9,0),TotalSpace)) * 100) AS [Percentage Free]

FROM ##_DriveInfo
ORDER BY [DriveLetter] ASC
GO

DROP TABLE ##_DriveSpace
DROP TABLE ##_DriveInfo

----- Trouble Shot -----------------
/* -- Error Message

Msg 15281, Level 16, State 1, Procedure sp_OACreate, Line 1
SQL Server blocked access to procedure 'sys.sp_OACreate' of component 'Ole Automation Procedures' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ole Automation Procedures' by using sp_configure. For more information about enabling 'Ole Automation Procedures', see "Surface Area Configuration" in SQL Server Books Online.
*/

use master
go
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO

------------------------------------------------------------------------------------

Thursday 4 February 2010

Date format in SQL Server 2005

Select getdate() -- 2010-02-05 10:03:44.527

-- To get all date format
select CONVERT(VARCHAR(12),getdate(),100) +' '+ 'Date -100- MMM DD YYYY' -- Feb 5 2010
union
select CONVERT(VARCHAR(10),getdate(),101) +' '+ 'Date -101- MM/DDYYYY'
Union
select CONVERT(VARCHAR(10),getdate(),102) +' '+ 'Date -102- YYYY.MM.DD'
Union
select CONVERT(VARCHAR(10),getdate(),103) +' '+ 'Date -103- DD/MM/YYYY'
Union
select CONVERT(VARCHAR(10),getdate(),104) +' '+ 'Date -104- DD.MM.YYYY'
Union
select CONVERT(VARCHAR(10),getdate(),105) +' '+ 'Date -105- DD-MM-YYYY'
Union
select CONVERT(VARCHAR(11),getdate(),106) +' '+ 'Date -106- DD MMM YYYY' --ex: 03 Jan 2007
Union
select CONVERT(VARCHAR(12),getdate(),107) +' '+ 'Date -107- MMM DD,YYYY' --ex: Jan 03, 2007
union
select CONVERT(VARCHAR(12),getdate(),109) +' '+ 'Date -108- MMM DD YYYY' -- Feb 5 2010
union
select CONVERT(VARCHAR(12),getdate(),110) +' '+ 'Date -110- MM-DD-YYYY' --02-05-2010
union
select CONVERT(VARCHAR(10),getdate(),111) +' '+ 'Date -111- YYYY/MM/DD'
union
select CONVERT(VARCHAR(12),getdate(),112) +' '+ 'Date -112- YYYYMMDD' -- 20100205
union
select CONVERT(VARCHAR(12),getdate(),113) +' '+ 'Date -113- DD MMM YYYY' -- 05 Feb 2010


SELECT convert(varchar, getdate(), 20) -- 2010-02-05 10:25:14
SELECT convert(varchar, getdate(), 23) -- 2010-02-05
SELECT convert(varchar, getdate(), 24) -- 10:24:20
SELECT convert(varchar, getdate(), 25) -- 2010-02-05 10:24:34.913
SELECT convert(varchar, getdate(), 21) -- 2010-02-05 10:25:02.990


---==================================
-- To get the time
select CONVERT(VARCHAR(12),getdate(),108) +' '+ 'Date -108- HH:MM:SS' -- 10:05:53

select CONVERT(VARCHAR(12),getdate(),114) +' '+ 'Date -114- HH:MM:SS:MS' -- 10:09:46:223
SELECT convert(varchar, getdate(), 22) -- 02/05/10 10:23:11 AM
----=============================================
SELECT getdate()+1
SELECT month(getdate())+1
SELECT year(getdate())+1