28.7.09

SQL Server error in backing up the database

I got a peculiar error while taking backup of my database.

Error received:

write on 'Physical backup filename(.bak format)' failed, status=33. See the SQL Server error log for more details. BACKUP DATABASE is terminating abnormally.


Explanation for this error:

Status=33 indicates the error should be related to the device. So there should be some problem with the storage device.

Reason for this issue:

If you try to take the backup of your database in a compressed harddrive. You will get this strange error. To resolve this, make your device(your D drive or E drive) un compressed and try to take the backup of your database.

It worked fine for me.

Thanks and Regards,

Venkatesan Prabu .J

Rand function and floor function in SQL Server

Rand function and floor function in SQL Server:

Most of the time, we need a functionality to generate random numbers in our application. SQL Server is offering a handy function to generate random numbers. Here is a small sample,

select rand()

The above query is used to fetch the value between 0 and 1. If I need to create a random number between 0 and 100.

Then, we need to multiply the function with 100.

SELECT 100*RAND()
The above query will fetch the recordds with decimal values which ranges from 0 to 100.



In case, If we need the value in Integer type. Then, we have to go for floor command which will remove the decimal part from the output.

SELECT floor(100*RAND())



In case, If you want to restrict the records between 2 to 100 (I dont want 0 and 1 to be retrieved). Then, we can use the below query.
SELECT floor(98*RAND())+2

Thanks and Regards,

Venkatesan Prabu .J

Stored procedure execution on SQL Server startup

Stored procedure execution on SQL Server startup:


I have studied a very interesting topic in SQL Server and wish to blog the same in my site.

Scenario:
On each SQL Server database startup, I need to execute a procedure in my database. It's a very basic scenario in all places.


Solution:
For this, SQL Server is providing an option of using a system stored procedure sp_procoption

-- Am creating a table
create table venkat1(id int, val varchar(10))
-- 'Am creating a procedure to insert a record in a table venkat1
create procedure Venkatesan_Insert_Procedure
as
begin
insert into venkat1(id,val) values (5,'F')
end
-- Am setting the sp_procoption for my procedure with the option name as "Startup" and option value as "True"


EXEC sp_procoption @ProcName = 'Venkatesan_Insert_Procedure',@OptionName = 'startup',@OptionValue = 'true'

After that, am restarting the server.

select * from venkat1


Thanks and Regards,

Venkatesan Prabu .J

Case Statement in SQL Server

Interesting facts about Case statement in SQL Server
--- Creating the table Venkat
drop table venkat
create table venkat(id int, val int ,date datetime,nam varchar(10))
insert into venkat values(1,200,'3/2/2008','venka')
insert into venkat values(1,100,'10/2/2008','venk')
insert into venkat values(3,400,'10/2/2008','arun')
insert into venkat values(3,500,'10/4/2008','balu')
insert into venkat values(3,600,'10/4/2008','lakshmi')
insert into venkat values(3,700,'10/4/2008','santhi')

--------------------------------------------------------
select * from venkat
--------------------------------------------------------

Case statement is used to check the alternatives.
"If the value is this much, show it as this. Else show it as this."

--------------------------------------------------------
-- A simple select statement for you
select id, value =

case
when val=100 then 'One Hundred'
when val=200 then 'Two Hundred'
when val=400 then 'Four Hundred'
when val=500 then 'Five Hundred'
when val=600 then 'Six Hundred'
when val=700 then 'Seven Hundred'
end

from venkat

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


--------------------------------------------------------
-- Complication in case statement
-- If i need to select two values based on one value. Then in this case, we need to write two case statement as below.
-- Instead of one case statement.
select id,
case
when val=100 then value ='One Hundred' and val = 'One'
when val=200 then value ='Two Hundred' and val = 'Two'
when val=400 then value ='Four Hundred' and val = 'Four'
when val=500 then value ='Five Hundred' and val = 'Five'
when val=600 then value ='Six Hundred' and val = 'Six'
when val=700 then value ='Seven Hundred' and val = 'Seven'
end

from venkat

--------------------------------------------------------
-- The above statement will throw error.
--------------------------------------------------------
select id, value =

case
when val=100 then 'One Hundred'
when val=200 then 'Two Hundred'
when val=400 then 'Four Hundred'
when val=500 then 'Five Hundred'
when val=600 then 'Six Hundred'
when val=700 then 'Seven Hundred'
end,
val=
case
when val=100 then 'One'
when val=200 then 'Two'
when val=400 then 'Four'
when val=500 then 'Five'
when val=600 then 'Six'
when val=700 then 'Seven'
end

from venkat

--------------------------------------------------------
-- My condition is to create a procedure with order by a column.
alter procedure venkatesanprabu_proc
(@options int)
as
begin

select id, value =

case
when val=100 then 'One Hundred'
when val=200 then 'Two Hundred'
when val=400 then 'Four Hundred'
when val=500 then 'Five Hundred'
when val=600 then 'Six Hundred'
when val=700 then 'Seven Hundred'
end

from venkat

order by
case
when @options=1 then id
when @options=2 then nam
end

end
--------------------------------------------------------
-- Case statement in Order by clause
--------------------------------------------------------
-- The above statement will throws an error.
-- An interesting fact in SQL Server is, we can't use different data type in the order by clause.
-- In the above statement, If it's option=1 then output will be order by id
-- Else if the option is equal to 2 then output will be order by nam.
--------------------------------------------------------
-- Here is the solution for the above problem. We need to use two case statement to resolve it.
--------------------------------------------------------
alter procedure venkatesanprabu_proc
(@options int)
as
begin

select id, value =

case
when val=100 then 'One Hundred'
when val=200 then 'Two Hundred'
when val=400 then 'Four Hundred'
when val=500 then 'Five Hundred'
when val=600 then 'Six Hundred'
when val=700 then 'Seven Hundred'
end

from venkat

order by
case
when @options=1 then id
end,
case
when @options=2 then nam
end

end
--------------------------------------------------------
exec venkatesanprabu_proc 1
exec venkatesanprabu_proc 2


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

Thanks and Regards,
Venkatesan Prabu .J

Dependent Objects in SQL Server

Identifying Dependency or relative objects in SQL Server:

I have seen an interesting question in a SQL Server forum.

Scenario:

How to identify the dependency on an object?

Solution:

Sp_depends “Object_Name”

Sp_depends will give you all the dependent objects in the databse. Let’s see the implementation for this scenario.

--- Creating the table Venkat
drop table venkat
create table venkat(id int, val int ,date datetime)
insert into venkat values(1,200,'3/2/2008')
insert into venkat values(1,100,'10/2/2008')
insert into venkat values(3,400,'10/2/2008')
insert into venkat values(3,500,'10/4/2008')
insert into venkat values(3,600,'10/4/2008')
insert into venkat values(3,700,'10/4/2008')

-- Created a view "vw" to fetch records from the table "Venkat"
--------------------------------------------------------
create view vw
as
select * from venkat
--------------------------------------------------------
-- Created a procedure named VenkatesanPrabu_proc with the statement to fetch records from the view
--------------------------------------------------------
create procedure VenkatesanPrabu_proc
as begin
select * from vw
end
select * from vw
--------------------------------------------------------
sp_depends vw


Thanks and Regards,
Venkatesan Prabu .J

SSIS with oracle database

Oracle error while migrating the data from one Oracle database to another:

Fortunately, I got a chance to work with oracle database migration using SSIS. Below is a peculiar behaviour of SQL Server Integration services. I have connected OLE DB source and connected to a table. Dragged and dropped OLE DB Destination, I need to created new table, clicked “New”.

The syntax for the table got created with a create statement.

CREATE TABLE SQLGenerated (
"Type_RATES_ID" NUMERIC(12),
"Type_RATES_VN" NUMERIC(12),
"_TYPE_ID" NUMERIC(12),
"_RATE_TYPE" VARCHAR(2),
"LENDING_RATE" NUMERIC (7,6),
"HEDGING_MARGIN" NUMERIC (7,6),
"PROFIT_MARGIN" NUMERIC (7,6),
"COMMISSION" NUMERIC (7,6),
"ESTABLISHMENT_COST" NUMERIC (24,8),
"RATE_PERIOD" NUMERIC(6),
"DATE_FIX" DATETIME,
"MOD_USER_ID" NUMERIC(12),
"MOD_TIMESTAMP" DATETIME,
"_ID" NUMERIC(12),
"TOTAL_RATE" NUMERIC (7,6),
"FIXED_AMOUNT" NUMERIC (24,8),
"_AMOUNT" NUMERIC (24,8),
"_TYPE_RATE_DIFF" NUMERIC (7,6),
"MATURITY_DATE" DATETIME,
"_SWITCH_FLAG" NUMERIC(1)
)


On pressing “OK” button, am getting the below error.
ORA-00902: invalid datatype (OraOLEDB)





To resolve this issue,
1. I went back to oracle database
2. Created a script for the source database.
3. Copied the content and pasted it into the create table window.
4. Now it’s working fine.
The problem is due to the data type,


create table OracleGenerated
(
Type_RATES_ID NUMBER(12) not null,
Type_RATES_VN NUMBER(12) not null,
_TYPE_ID NUMBER(12) not null,
_RATE_TYPE CHAR(2),
LENDING_RATE NUMBER(7,6),
HEDGING_MARGIN NUMBER(7,6),
PROFIT_MARGIN NUMBER(7,6),
COMMISSION NUMBER(7,6),
ESTABLISHMENT_COST NUMBER(24,8),
RATE_PERIOD NUMBER(6),
DATE_FIX DATE,
MOD_USER_ID NUMBER(12),
MOD_TIMESTAMP DATE,
_ID NUMBER(12) not null,
TOTAL_RATE NUMBER(7,6),
FIXED_AMOUNT NUMBER(24,8),
_AMOUNT NUMBER(24,8) default 0 not null,
_TYPE_RATE_DIFF NUMBER(7,6) default 0 not null,
MATURITY_DATE DATE,
_SWITCH_FLAG NUMBER(1) default 0,
)
The problem is due to the datatype “Datetime”. SQL Server is generating datetime but oracle is not supporting the same. In turn, we need to modify the data type to “date” type.

Thanks and Regards,

Venkatesan Prabu .J

General options in SQL Server

General tools options in SQL Server:

Contolling the SQL Server editor window in SQL Server Management studio.

Goto Tools->Options-> Query execution->General, we are having lot of options.

1. Set Rowcount – This option is used to restrict the result set returned by the text editor.
Considering am having lakhs of records and I need to restrict the number of records returned, we can specify the same. It’s equivalent to the TOP keyword. “0” indicates that, there will be unlimited rows (or) no restrictions in the number of records fetched.


2. Set Textsize – This option is used to restrict the size of the text to be returned in your text editor. Considering, am having a column of type “TEXT”, If I have given 10 as the bytes. The resultset will be restricted with only 10 bytes.

3. Execution time-Out : We can restrict the query execution time. How much time, the query should execute. If we have given 0 as the value, then its unlimited or no restriction. This is very useful in executing a query in production environment.

4. Batch separator: This is used to separate the batch statement. Grouping the queries.
Strange but interesting facts of the GO statement. Before this article, I thought like the go statement will commit the transactions. But after checking this, I got shocked. It’s not committing it. I have tried to rollback the statement. The entire process got roll backed.


begin transaction
go
insert into venkat values(3,700,'10/4/2008')
go
insert into venkat values(3,700,'10/4/2008')
rollback

So, GO statement in SQL Server is used only for separating the SQL statements and it doesn’t have any impact on the transactions handling.








Thanks and Regards,

Venkatesan Prabu .J

Foreign key constraints in SQL Server

Foreign key constraints :

This constraint is used to map a particular column in the child table with a primary key column in the parent table. Consider my scenario, am having an employee table and it will be having empid as primary key (Unique reference to identify an employee) , am having empProjects which will hold project id as the primary key.

I need to check, In which project an employee is allocated? Or what are the projects assigned for this particular employee?

The relation ship between these two tables is One to Many relationship (An employee can work in more than one project).

To retrieve the result set we need to have a foreign key relation ship between the employee table and empProjects table, a column empid should be created in empProjects table and it should refer the primary table “Employee”.

Let’s see a small example; I am trying to create two tables VenkatA, VenkatB. Id in the second table is referencing the ‘id’ column in the primary table.


create table venkatA(id int,[name] varchar(100))
create table venkatB(id int references venkatA(id),designation varchar(100))


OOPS, On executing the query above, we will get an exception.
There are no primary or candidate keys in the referenced table 'venkatA' that match the referencing column list in the foreign key 'FK__venkatB__id__7BB05806'.


It’s because of the column ‘id’ in the primary table. It’s mandatory to declare that particular columns as primary or candidate key.

create table venkatA(id int primary key,[name] varchar(100))
create table venkatB(id int references venkatA(id),designation varchar(100))


On executing the query above, you will get the second table referencing the first one.



Thanks and Regards,

Venkatesan Prabu


Phyical MDF and LDF location in SQL Server

I have started questioning myself like,

Is it possible to retrieve the physical location of my data file and log file?

I am struck up with retrieving details for data and log file location of our existing databases and found that the key table is located in the master databases. Below is the query to retrieve that information,

select * from [master].[sys].[master_files]

On executing the query above, we will get the below result set,

Now, lets tune up the query further, I am trying to retrieve data files physical path for my master database.

DECLARE @sql_path NVARCHAR(256) ;

SELECT @sql_path = SUBSTRING([physical_name], 1, CHARINDEX(N'master.mdf', LOWER([physical_name])) - 1)
FROM [master].[sys].[master_files]
WHERE [database_id] = 1
AND [file_id] = 1 ;
print @sql_path

The output is “C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\”

Thanks and Regards,

Venkatesan Prabu .J

17.7.09

Attaching and Detaching SQL Server database

Attaching and Detaching the database:
Restoring the database can be achieved by taking the backup of the database and restoring it (or) attaching the mdf and ldf files.
In this article, let’s see how we are attaching the database through mdf and ldf files.

Detaching the database:
First, let me detach the existing database and we will attach the same.
Steps:
1. Right click on the database and select tasks -> Detach.





1. We will get a detach database window with the database listed down.
Options to be noted down:


a. Drop Connections: This option will drop the connection between the database and the server and detach the database.


b. Update Statistics: This option will update the recent statistics of the database and afterwards proceed with the detach option.


c. Keep Full Text catalogs: This option will create full text catalogs on the database and proceed with the detaching the database.


d. Status: Indicates, whether the database is ready to proceed any action on it.

2. Click “OK” to proceed further on this.


3. The database will get detached from the server. You can’ see the database.



Attaching the database:


Right click on the database and select “Attach” option.


You will get Attach database window,


We need to add the “mdf” file location by clicking “ADD” button in the above window.

Select the mdf file.


The bottom database details will get populated automatically. Click “OK” button. The database will get attached to the server.

Thanks and Regards,
Venkatesan Prabu .J

15.7.09

Count of records group by month in SQL Server

Scenario:



Am trying to group the records(count) based on the month. How can we achieve it?



Solution:

drop table venkat
create table venkat(id int, date1 datetime,date2 datetime)
insert into venkat values(1,'1/2/2009','3/3/2009')
insert into venkat values(1,'2/2/2009','4/3/2009')
insert into venkat values(2,'2/2/2009','3/3/2009')
insert into venkat values(2,'2/2/2009','4/3/2009')


select * from venkat


select

"MonthName"=
case when datepart(month,date1) =1 then 'January'
when datepart(month,date1) =2 then 'February'
end ,

count(*) as CountByMonth
from venkat group by datepart(month,date1)

Thanks and Regards,

Venkatesan Prabu .J

Difference between the dates group by id

Scenario:

I got a nice question in a forum on getting the difference between the created date and the updated date for a particular id. The complication is, we will have lot of records with that id. We need to group it.


Solution:

The solution is too simple,


drop table venkat
create table venkat(id int, date1 datetime,date2 datetime)
insert into venkat values(1,'1/2/2009','3/3/2009')
insert into venkat values(1,'2/2/2009','4/3/2009')
insert into venkat values(2,'2/2/2009','3/3/2009')
insert into venkat values(2,'2/2/2009','4/3/2009')
select * from venkat
select id,datediff(dd,min(date1),max(date2)) as datedifferenc from venkat group by id

Thanks and Regards,

Venkatesan Prabu .J

DateAdd function in SQL Server


drop table aa
create table aa(col1 datetime,col2 datetime)


I need to insert some records in the table. I need today’s date in the first column and tomorrow’s date in the second column. This can be achieved by using dateadd function.

Dateadd function:

Suppose, I need to add the date by 1 day. The syntax for this is,

Dateadd(dd,1,datecolumn)

The value 1 can be replaced with any number, based on your requirement.

insert into aa values(getdate(),dateadd(dd,1,getdate()))


If I want my previous date, we can use negative value as below.

insert into aa values(getdate(),dateadd(dd,-1,getdate()))

Dateadd function with year changes:

insert into aa values(getdate(),dateadd(yy,1,getdate()))



Similarly, we can proceed with date/hour/minutes and seconds.

Thanks and Regards,

Venkatesan Prabu .J

14.7.09

Data type error in SSIS with oracle database

SQL Server Intergration services (SSIS) with Oracle database:

Fortunately, I got a chance to work with oracle database migration using SSIS. Below is a peculiar behaviour of SQL Server Integration services. I have connected OLE DB source and connected to a table. Dragged and dropped OLE DB Destination, I need to created new table, clicked “New”.

The syntax for the table got created with a create statement,

CREATE TABLE SQLGenerated (
"Type_RATES_ID" NUMERIC(12),
"Type_RATES_VN" NUMERIC(12),
"_TYPE_ID" NUMERIC(12),
"_RATE_TYPE" VARCHAR(2),
"LENDING_RATE" NUMERIC (7,6),
"HEDGING_MARGIN" NUMERIC (7,6),
"PROFIT_MARGIN" NUMERIC (7,6),
"COMMISSION" NUMERIC (7,6),
"ESTABLISHMENT_COST" NUMERIC (24,8),
"RATE_PERIOD" NUMERIC(6),
"DATE_FIX" DATETIME,
"MOD_USER_ID" NUMERIC(12),
"MOD_TIMESTAMP" DATETIME,
"_ID" NUMERIC(12),
"TOTAL_RATE" NUMERIC (7,6),
"FIXED_AMOUNT" NUMERIC (24,8),
"_AMOUNT" NUMERIC (24,8),
"_TYPE_RATE_DIFF" NUMERIC (7,6),
"MATURITY_DATE" DATETIME,
"_SWITCH_FLAG" NUMERIC(1)
)


On pressing “OK” button, am getting the below error.

ORA-00902: invalid datatype (OraOLEDB)

To resolve this issue,
1. I went back to oracle database
2. Created a script for the source database.
3. Copied the content and pasted it into the create table window.
4. Now it’s working fine.


The problem is due to the data type,

create table OracleGenerated
(
Type_RATES_ID NUMBER(12) not null,
Type_RATES_VN NUMBER(12) not null,
_TYPE_ID NUMBER(12) not null,
_RATE_TYPE CHAR(2),
LENDING_RATE NUMBER(7,6),
HEDGING_MARGIN NUMBER(7,6),
PROFIT_MARGIN NUMBER(7,6),
COMMISSION NUMBER(7,6),
ESTABLISHMENT_COST NUMBER(24,8),
RATE_PERIOD NUMBER(6),
DATE_FIX DATE,
MOD_USER_ID NUMBER(12),
MOD_TIMESTAMP DATE,
_ID NUMBER(12) not null,
TOTAL_RATE NUMBER(7,6),
FIXED_AMOUNT NUMBER(24,8),
_AMOUNT NUMBER(24,8) default 0 not null,
_TYPE_RATE_DIFF NUMBER(7,6) default 0 not null,
MATURITY_DATE DATE,
_SWITCH_FLAG NUMBER(1) default 0,
)
The problem is due to the datatype “Datetime”. SQL Server is generating datetime but oracle is not supporting the same. In turn, we need to modify the data type to “date” type.

Thanks and Regards,
Venkatesan Prabu .J

Renaming SQL Server objects

Renaming SQL Server objects like table/Index/functions:

Renaming the object is a very challenging and interesting part in SQL Server.

Scenario: I have created a table and my boss is asking me to change the name of the table.
How can I achieve it? This can achieved using sp_rename

Let's see, how we are achieving it

Creating the table named Venkat with two column id and nam
create table Venkat(id int,nam varchar(10))
Am trying to create an index on the column id on the table venkat
create clustered index Venkat_Index on venkat(id )
--------------------------------------------------------------------

Renaming the index name on the table venkat
The syntax is,
exec sp_rename 'tablename.OldIndexID','new index name','index'
Example,
exec sp_rename 'venkat.venkat_index','Venkat_modified_index','index'
--------------------------------------------------------------------

Renaming the column name on the table venkat
The syntax is,
exec sp_rename 'tablename.OldColumnID','new Column name','column'
Example,
exec sp_rename 'venkat.id','id1','column'
--------------------------------------------------------------------

Renaming the name of the table
The syntax is,
exec sp_rename 'OldTableName','new Table Name'
Example,
exec sp_rename 'venkat','New_Venkat'

--------------------------------------------------------------------
While using this option, we used to get the below message from SQL Server
Caution: Changing any part of an object name could break scripts and stored procedures.
It indicates that the relative objects will get affected due to this change.
---------------------------------------------------------------------

Thanks and Regards,
Venkatesan Prabu .J