26.4.09

Check option in SQL Server views

CHECK option in views:

Views are nothing but an external skeleton for a table. In order to avoid direct access to the table + If we have multiple tables to be linked to obtain a single output. We will use views.

if exists (select * from sys.objects where name='venkat')
begin
drop table venkat
end
if not exists (select * from sys.objects where name='venkat')
begin
create table venkat(id int, name varchar(20),name1 varchar(20))
end
insert into venkat
select 1,'venkat','venkat1'
union all
select 2,'arun','arun1'
union all
select 3,'lakshmi','lakshmi1'
union all
select 4,'karthi','karthi1'
go

insert into venkat select 6,'sajhklg','kjhl55'
--select * from sys.messages ]
drop view venkatview

-- Check option is used to restrict the data by validating at the view level
create view venkatview
as
select * from venkat where id>3 with check option

If we try to execute the below insert statement,
insert into venkatview select 0,'suba','suba1'
We will get an error message,
Msg 550, Level 16, State 1, Line 1
The attempted insert or update failed because the target view either specifies WITH CHECK OPTION or spans a view that specifies WITH CHECK OPTION and one or more rows resulting from the operation did not qualify under the CHECK OPTION constraint.
The statement has been terminated.

Thanks and Regards,
Venkatesan Prabu .J

Inserting multiple records using single insert statement

An Interesting topic with Insert statement,
Is it possible to insert multiple records using one single insert statement.
Let's see,
-- If table exists, drop the table
drop table venkat
create table venkat(id int, name varchar(10))
insert into venkat
select 1,'Venkat'
union all
select 2,'arun'
union all
select 3,'Lakshmi'
union all
select 4,'arun'
union all
select 5,'ve'
select * from venkat

Thanks and Regards,
Venkatesan Prabu .J

Error Messages in SQL Server

Error messages or exceptions in SQL Server:
Error messages thrown in case of error is stored in sys.messages SQL Server table.
Below are the columns available in this table.
1. Message_id - Unique id to identify the error.
2. Language_id - Specifies the language of the message stored. (1033 indicates English)
3. Severity - Severity of the message.
4. is_event_logged - 0 indicates, the message won't get logged in the Eventviewer.
1 indicates the message will get logged in the Eventviewer.
5. Text - text displayed to the user incase of showing error.



If we want to check the content of this table,
use master
select * from sys.messages



Happy Learning!!!

Thanks and Regards,

Venkatesan Prabu .J

Self Join + Case statement in SQL Server

Self Join:

Joining the table itself is referred to as self join.

Case statement:

Case statement is used to check the condition

-- Creating tables for our sample
drop table venkat
drop table original
create table venkat(id int)
insert into venkat values(10)
insert into venkat values(11)
insert into venkat values(12)
insert into venkat values(13)
insert into venkat values(14)
----------------------------------------------------
create table Original(id int)
insert into Original values(1)
insert into Original values(2)
insert into Original values(3)
----------------------------------------------------
select * from original
select * from venkat

-- How to use case statement in SQL Server
select a.id from venkat a inner join
(select
case id
when 1 then 10
when 2 then 11
when 3 then 12
end as id
from original)t on a.id=
t.id

--- Self join with the same table.
select a.id from venkat a inner join
(select id from venkat)t on a.id=
t.id

Happy Learning!!!
Thanks and Regards,

Venkatesan Prabu .J

Query governor in SQL Server

Query governor cost limit:

This option is used to set the time to be taken to execute a query.
If the value is 0, then the time limit is indefinite. Where as, if we provide
positive value. The query will be executed upto that particular time.

For server level settings [For all the users]:
If we want to set this value for the whole server irrespective of the users, we can acheive it using
sp_configure option.
sp_configure 'QUERY_GOVERNOR_COST_LIMIT',1
reconfigure

Whereas, If we need to set the same for specific connection. We can use the set command.

SET QUERY_GOVERNOR_COST_LIMIT 1 Thanks and Regards,
Venkatesan Prabu .J

T-SQL Challenges - Fetching the first and last record from the table

Problem statement:
Considering am having lot of records(Bank transaction) in a table.
1. I want the account number which repeats more than one times.
2. After filtering the records in the above criteria, I need only the first transaction and the last transaction.
How can we achieve it? Lets see,
-- Am creating the table
create table venkat(id int, id1 int,nam varchar(10))
insert into venkat values(1,1,'Venkat')
insert into venkat values(1,2,'Venkat')
insert into venkat values(1,3,'Venkat')
insert into venkat values(1,4,'Venkat')
insert into venkat values(1,5,'Venkat')
insert into venkat values(2,5,'Venkat')
select * from venkat

This kind of problem can be resolved using Common Table expression (a new feature in SQL Server 2005). CTE enable us to divide a huge query into smaller chunks and we can easily write a complex logic in simple terms.

with cte as
(
select * from
(
select count(id) as cnt,id from venkat group by id
-- Getting the records with more than 1 record
)t where cnt >1
),
cte1 as
(
select row_number()over(partition by id order by id1 ) as rownumber ,id,id1,nam from venkat
where id in (select id from cte)
-- Partitioning the records using rownumber partition concept
)
,
cte2 as
(
select * from cte1 where (rownumber=1 OR rownumber = (select max(rownumber) from cte1))
-- Fetching only 1 and last record in each individual clients
)
select * from cte2

Regards,
Venkatesan Prabu .J

14.4.09

Conditional Joins in SQL Server

An interesting article on conditional joins in sql server:
I have come across a very different peculiar scenario to join a column based on the conditions.
1. If the column value is not null join with the columnA.
2. If the column value is null join with columnB in the same table.
How can we achieve this?
-- creating temporary tables
drop table venkat
create table venkat(id int, name varchar(100))
insert into venkat values(1,'venkat1')
insert into venkat values(2,'venkat2')
insert into venkat values(3,'venkat3')
insert into venkat values(4,'venkat4')
drop table venkat1
create table venkat1(id int,id1 int, name1 varchar(100))
insert into venkat1 values(1,null,'venkat1')
insert into venkat1 values(2,null,'venkat2')
insert into venkat1 values(null,3,'venkat3')
insert into venkat1 values(4,null,'venkat4')
select * from venkat1
select * from venkat
-- Option 1
select * from venkat a
inner join venkat1 b on a.id=
case isnull(b.id,0)
when 0 then b.id1
else
b.id
end
-- Option2
select * from venkat a
inner join venkat1 b on a.id=isnull(b.id,b.id1)
-- column values
select a.id,a.name,isnull(b.id,b.id1) as TableBID from venkat a
inner join venkat1 b on a.id=isnull(b.id,b.id1)

Thanks and Regards,
Venkatesan Prabu .J

13.4.09

Pattern matching in SQL Server

Pattern matching is a very important topic in SQL Server. It enable us to get the relative or exact pattern of data from the database. Pattern matching can be easily achieved through LIKE operator in the where clause.

% - Operator is used to fetch 0 or any number of characters and
_ - Operato is used to identify one character at its place. L

Lets see some example to learn more,
-- Creating a table and inserting some dummy data into that table.
drop table venkat
create table venkat(id int, name varchar(10))
insert into venkat
select 1,'Venkat'
union all
select 2,'arun'
union all
select 3,'Lakshmi'
union all
select 4,'arun'
union all
select 5,'ve'
--String Starts with "V" and having any number of characters. % indicates any number of character
select * from venkat where name like 'V%'
--String Starts with "V" and having only one character. _ indicates only one number.
select * from venkat where name like 'V_'
--String should not start with "V"
select * from venkat where name not like 'V%'
Thanks and Regards,
Venkatesan Prabu .J

Recent data from sql server table - TSQL Challenges

Scenario:
Considering, lot of empoloyees with different roles were working in a office. I want to list down the employees recent job role. Is it possible?

What are the complications in this, am having a table listing down the employee role and its role change date. I need to fetch the recent date and the recent employees role.

-- Creating temporary tables
drop table emp
drop table emprole
create table Emp(Employeeid int, roleid int,Updtdate datetime)
create table EmpRole(Roleid int, RoleName varchar(10))

-- Inserting data into the temporary tables
insert into emp values(1,33,'2008-10-11')
insert into emp values(1,44,'2008-10-13' )
insert into emp values(2,55,'2008-10-14')
insert into emp values(2,66,'2008-10-16')


insert into emprole values(33, 'Mgr')
insert into emprole values(44, 'Dev')
insert into emprole values(55, 'Tester')
insert into emprole values(66, 'Lead')

-- Output for the below three select statements
select * from Emp

select * from EmpRole

select Employeeid,rolename from
(
select Employeeid, row_number() over (partition by employeeid
order by UpdtDate desc) as row ,r.rolename
from emp e inner join emprole r on e.roleid=r.roleid
)tblw where row=1



Thanks and Regards,
Venkatesan Prabu .J

Stored Procedure inside another stored procedure

Its pretty interesting topic, a basic one too.
This article will answer you the below questions,
1. Is it possible to execute a stored procedure inside a stored procedure?
2. How to insert a data into a table from stored procedure output?

-- Am trying to create temporary tables
create table venkattable(id int, name1 varchar(100))
create table venkattable1(id int, name1 varchar(100))
-- Inserting data into my table
insert into venkattable values(1,'Venkat1')
insert into venkattable values(2,'Venkat2')
insert into venkattable values(3,'Venkat3')
insert into venkattable values(4,'Venkat4')
insert into venkattable values(5,'Venkat5')
insert into venkattable values(6,'Venkat6')
select * from venkattable


--Creating first stored procedure

create procedure venkatproc1
as begin
select * from venkattable where id=2
end
exec venkatproc1

--Creating second stored procedure
create proc venkatproc2
as begin

-- Output of a stored procedure into a sql server table
insert venkattable1 exec venkatproc1
end
exec venkatproc2

-- Checking for the output
select * from venkattable1

Thanks and Regards,

Venkatesan Prabu .J

My T-SQL Gallery @code.msdn.microsoft


Created my own T-SQL Gallery in Microsoft site. Do visit the same and share your feedback,

http://code.msdn.microsoft.com/VenkatSQLSample/Thread/List.aspx

Thanks and Regards,
Venkatesan Prabu .J

SQL Server Interview questions - Part 1

What is the significance of NULL value and why should we avoid permitting null values?
Null means no entry has been made. It implies that the value is either unknown or undefined.We should avoid permitting null values because Column with NULL values can't have PRIMARY KEY constraints. Certain calculations can be inaccurate if NULL columns are involved.

What is SQL whats its uses and its component ?
The Structured Query Language (SQL) is foundation for all relational database systems. Most of the large-scale databases use the SQL to define all user and administrator interactions. It enable us to retrieve the data from based on our exact requirement. We will be given a flexibility to store the data in our own format.


The DML component of SQL comprises four basic statements:
* SELECT to get rows from tables
* UPDATE to update the rows of tables
* DELETE to remove rows from tables
* INSERT to add new rows to tables


What is DTS in SQL Server ?
Data Transformation Services is used to transfer the data from one source to our required destination. Considering am having some data in sql server and I need to transfer the data to Excel destination. Its highly possible with dialogue based tool called Data Transformation services. More customization can be achieved using SSIS. A specialized tool used to do such migration works.


What is the difference between SQL and Pl/Sql ?

Straight forward. SQL is a single statement to finish up our work.Considering, I need some data from a particular table. “Select * from table” will fetch the necessary information. Where as I need to do some row by row processing. In that case, we need to go for Procedural Logic / SQL.

What is the significance of NULL value and why should we avoid permitting null values?
Null means no entry has been made. It implies that the value is either unknown or undefined.We should avoid permitting null values because Column with NULL values can't have PRIMARY KEY constraints. Certain calculations can be inaccurate if NULL columns are involved.

Difference between primary key and Unique key?
Both constraints will share a common property called uniqueness. The data in the column should be unique. The basic difference is,
· Primary key won’t allow null value. Whereas, unique key will accept null value but only one null value.
· On creating primary key, it will automatically format the data inturn creates clustered index on the table. Whereas, this characteristics is not associated with unique key.
· Only one primary key can be created for the table. Any number of Unique key can be created for the table.

Select Statement in SQL Server

Select Statement in SQL Server

String Functions in sql server

String Functions in sql server
Substring/Len/replace/Ltrim/Rtrim

SQL Server Interview Question - Part 2

What is normalization?

Normalization is the basic concept used in designing a database. Its nothing but, an advise given to the database to have minimal repetition of data, highly structured, highly secured, easy to retrieve. In high level definition, the Process of organizing data into tables is referred to as normalization.


What is a stored procedure:
Stored procedures are precompiled T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements. As, its precompiled statement, execution of Stored procedure is compatatively high when compared to an ordinary T-SQL statement.


What is the difference between UNION ALL Statement and UNION ?
The main difference between UNION ALL statement and UNION is UNION All statement is much faster than UNION,the reason behind this is that because UNION ALL statement does not look for duplicate rows, but on the other hand UNION statement does look for duplicate rows, whether or not they exist.

Example for Stored Procedure?
They are three kinds of stored procedures,1.System stored procedure – Start with sp_2. User defined stored procedure – SP created by the user.3. Extended stored procedure – SP used to invoke a process in the external systems.Example for system stored proceduresp_helpdb - Database and its propertiessp_who2 – Gives details about the current user connected to your system. sp_renamedb – Enable you to rename your database


What is a trigger?

Triggers are precompiled statements similar to Stored Procedure. It will automatically invoke for a particular operation. Triggers are basically used to implement business rules.


What is a view?
If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specfic users to see only specific columns based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time.


What is an Index?
When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index.


What are the types of indexes available with SQL Server?

There are basically two types of indexes that we use with the SQL ServerClustered -

1. It will format the entire table, inturn physically sort the table.

2. Only one clustered index can be created for a table.

3. Data will be located in the leaf level.

4. By default, primary key will create clustered index on the table.

Non-Clustered Index

1. It wont touch the structure of the table.

2. It forms an index table as reference to the exact data.

3. A reference to the data will be located in the leaf level.

4. For a table, we can create 249 non clustered index.

Happy Learning!!!
Regards,
Venkatesan Prabu .J

SQL Interview question

Extent Vs Page?

Pages are low level unit to store the exact data in sql server. Basically, the data will be stored in the mdf, ldf, ndf files. Inturn, pages are logical units available in sql server.The size of the page is 8KB.

Eight consecutive pages will form an extent 8 * 8KB = 64KB.

Thus I/O level operation will be happening at pages level.The pages will hold a template information at the start of each page (header of the page).

They are,

1. page number,

2. page type,

3. the amount of free space on the page,

4. the allocation unit ID of the object that owns the page.

Extents will be classifed into two types,

1. Uniform extents

2. Mixed extents

Uniform Extents:It occupied or used by a single object. Inturn, a single object will hold the entire 8 pages.Mixed

Extents:Mulitple objects will use the same extent. SQL Server will allow a max of eight objects to use a shared extent.

Property of SQL Server :Initally if an object is created, sql server will allocate the object to the mixed extent and once if the size reaches 8 pages and more... immediately, a new uniform extent will be provided for that particular object.

Herecomes, our fragmentation and reindexing concepts.



Best Joke - Enjoy it

Best Joke - Enjoy it