31.5.09

Deny statement in SQL Server

I got a peculiar request to restrict a user from specific actions on a table.

Condition:
Restrict a user from inserting/updatin/deleting the records in a specific table.

Solution:

We can use deny statement to achieve this task. Below is the query for the same,

DENY INSERT, UPDATE, DELETE
ON aa
TO venkat

Thanks and Regards,
Venkatesan Prabu .J

ISNULL function in SQL Server

ISNULL function in SQL Server:


IsNull function is an important function and frequently used function in SQL Server.
It's used to handle null value in SQL Server table. If we are having null value in the table data.
How to handle it? or Do we need to display any alternative value or not? ISNULL function will
answer your questions.


Syntax:
Isnull(columnname,String to be replaced)
It indicates if the column value is null then replace it the given string.
Below is the sample query for the same,


create table aa1(id int,name char(10))
create table aa(id int,name char(10))
insert into aa values(1,'venkat')
insert into aa values(2,null)
insert into aa values(3,null)
insert into aa values(4,'Arun')
select * from aa
select id,isnull(name,'No data') as name from aa




Happy Learning!!!
Thanks and Regards,
Venkatesan Prabu .J

30.5.09

Update using cursor in Oracle

My first ariticle in Oracle:

Nowadays, am becoming oracle developer in develping some funny scripts. Obviosly, am maintaining some standards in writing my scripts. In my first article, I am trying to update a table based on the records from the second table.

-- Am trying to create two new tables.
create table aa1(id int,name char(10))

create table aa(id int,name char(10))

insert into aa values(1,'venkat')

insert into aa1 values(1,'venkat1')

-------------Venkat's First Oracle Cursor -------------------------
create or replace procedure Venkat_FirstOracleCursor as
cursor cur_SubLoans is

select id from aa;begin for id1 in cur_SubLoans loop

begin

for id1 in cur_SubLoans loop

update aa1 sid set sid.id = 0 where sid.id = id1.id;

end loop;

end Venkat_FirstOracleCursor;

29.5.09

update with Inner join in SQL Server

Update Statement with join between two tables :

I got a chance to join two different tables and update one or more tables involved in join.

Oops, this syntax is not working in Oracle. I have tried it in my PL/SQL window. Strange :-(

-- Am creating new tables

create table aa1(id int,name char(10))
create table aa(id int,name char(10))

-- Am inserting my records in the table
insert into aa values(1,'venkat')
insert into aa1 values(1,'venkat1')

-- Selecting records from the table

select * from aa
select * from aa1

-- Query to update the table with join operator
update aa set aa.id=2
from aa inner join aa1 on aa.id=aa1.id

But, this query won't work in Oracle... hats off SQL Server. You are really great...

Happy learning!!!

Thanks and Regards,
Venkatesan Prabu .J

25.5.09

Shortcut to SQL Server 2008 SSMS

SQL Server 2008 (Shotcut for Management studio) :

In SQL Server 2005, we had sqlwb as the shortcut text to open SQL Server 2005 Management studio. I have tried the same for SQL Server 2008 but end up in vain.

Instead, we need to use SSMS to get SQL Server 2008 Management studio. Nice na...



Thanks and Regards,
Venkatesan Prabu .J

Union operator in sql server

UNION Operator in SQL Server:

Union operator is used to merge the records from first table with the records from the second table.



Some conditions:

1. It's used to fetch the records from two or more tables into a single result set.
2. The union columns should be of same data type.
3. Union operator will remove the duplicates from the result set.

Am trying to put union between the tables with same column types,

drop table venkat1
create table venkat1(id int, rating int, dat datetime,auditrecord int)
insert into venkat1 values(1,1,'7/1/2006',1)
insert into venkat1 values(1,3,'7/1/2006',2)
insert into venkat1 values(1,5,'7/2/2006',3)
insert into venkat1 values(1,2,'8/10/2006',4)
insert into venkat1 values(2,4,'8/7/2006',1)
select * from venkat1
create table venkat2(id int, rating int)
insert into venkat2 values(6,1)
insert into venkat2 values(7,3)
insert into venkat2 values(8,5)
insert into venkat2 values(9,2)
select * from venkat2
select id,rating from venkat1
union
select id,rating from venkat2



Everything seems to be fine. Now, am trying with bit different data type.. replacing integer column with varchar column. Let's see what's happening.


drop table venkat2
create table venkat2(id int, rating decimal(5,2))
insert into venkat2 values(6,1)
insert into venkat2 values(7,3)
insert into venkat2 values(8,5)
insert into venkat2 values(9,2)
select * from venkat2
select id,rating from venkat1
union
select id,rating from venkat2



OOPS, no error instead the entire result set will be associated with decimal column.
By execution, the result set will be taking the highest refining column type to accomodate both
the data types. Nice to see...


drop table venkat2
create table venkat2(id int, rating varchar(10))
insert into venkat2 values(6,'Number 1')
insert into venkat2 values(7,'Number 3')
insert into venkat2 values(8,'Number 5')
insert into venkat2 values(9,'Number 2')

select id,rating from venkat1
union
select id,rating from venkat2

We are getting an error,


Conversion failed when converting the varchar value 'Number 1' to data type int.


Checking for the unique property of the union operator:
I have added a new row, which has duplicate record and am doing an union operator.

drop table venkat2
create table venkat2(id int, rating decimal(5,2))
insert into venkat2 values(6,1)
insert into venkat2 values(7,3)
insert into venkat2 values(8,5)
insert into venkat2 values(9,2)
insert into venkat2 values(9,2)
select id,rating from venkat1
union
select id,rating from venkat2

Difference between Union and Union all operator:
Here comes the difference between the above two, Union all will give all the records including duplicates whereas union operator will remove the duplicates.


Thanks and Regards,
Venkatesan Prabu .J

Convert function in SQL Server

I got a peculiar request to convert the datetime format.



A user is having the datetime format in month/day/year and he want to store the data in the format of day/month/year. (A typical datetime format operation in sql server).

It can be achieved using convert function,

Convert function will convert the data into required format. The syntax is,
Convert(datatype, data (or) columnname , format you want)

For example,
convert(varchar(10),dat,103) will fetch the output in the format of date/month/year format.

Let's see a small example to check it.

drop table venkat1
create table venkat1(id int, rating int, dat datetime,auditrecord int)
insert into venkat1 values(1,1,'7/1/2006',1)
insert into venkat1 values(1,3,'7/1/2006',2)
insert into venkat1 values(1,5,'7/2/2006',3)
insert into venkat1 values(1,2,'8/10/2006',4)
insert into venkat1 values(2,4,'8/7/2006',1)
select * from venkat1

select dat from venkat1
select convert(varchar(10),dat,103) from venkat1
select convert(varchar(10),dat,101) from venkat1


Another option, a lengthy operation of doing the above functionality

select convert(datetime,convert(varchar(10),day(dat) ) +'/'+ convert(varchar(10),month(dat) ) +'/' + convert(varchar(10),year(dat)))as da from venkat1

Happy Learning!!!

Thanks and Regards,

Venkatesan prabu .J

24.5.09

Dynamic queries with varchar as input variable

Dynamic queries:



For this month, am bit concentrating on dynamic queries. I found lot of interesting things in dynamic queries and wish to blog the same.


This article primarily deals with dynamic query with varchar as input variable

-- Am creating a table named customers

drop table Customers
CREATE TABLE Customers
(
Cus_ID int PRIMARY KEY ,
Cus_Name varchar(30) NOT NULL,
Cus_City varchar(30) NOT NULL,
Cus_Country varchar(30) NOT NULL
)
insert into customers values(1,'venkat','dpi','india')
select * from customers

In the below query am assigning the value to the variable. For dynamic queries, providing an input value will be bit different. We need to use 3 single quotes before and after the input value.

DECLARE @SQL varchar(1000)
declare @cus_name varchar(1000)
declare @Cus_City varchar(1000)
declare @Cus_Country varchar(1000)


set @Cus_Name ='''venkat'''
SET @SQL = 'SELECT Cus_Name, Cus_City, Cus_Country FROM Customers '
SET @SQL = @SQL + 'WHERE '
SET @SQL = @SQL + 'Cus_Name =' + @cus_Name

print @sql

EXEC(@SQL)


Print @sql will provide you the output "
SELECT Cus_Name, Cus_City, Cus_Country FROM Customers WHERE Cus_Name ='venkat'

The above query is executed dynamically.

Thanks and Regards,

Venkatesan prabu .J

Row to Column - T SQL Challenge (Group by month)

This one is pretty interesting article among my best articles in this blog.


In this article am trying to do some T-SQL tweaks to achieve a complex functionality. Let me stop exaggregating the things and proceed with my problem and solutions for the same.



Problem Statement:

Its a typical row to column problem in SQL Server (Its my favourite as usual) .


Am having the person whose ratings will be changing differently in a month. I want to sum all the ratings of a person for a month providing the input month is given to you Considering July and august as the month.




If you read further more on the sample, you can understand, what am trying to achieve in SQL Server.



create table venkat1(id int, rating int, dat datetime,auditrecord int)
insert into venkat1 values(1,1,'7/1/2006',1)
insert into venkat1 values(1,3,'7/1/2006',2)
insert into venkat1 values(1,5,'7/2/2006',3)
insert into venkat1 values(1,2,'8/10/2006',4)
insert into venkat1 values(2,4,'8/7/2006',1)
select * from venkat1


Now, am trying to use row_number concept to fetch the ratings of the individual based on the month. After getting this input, I am inserting the same to a temporary table.


Below is the query for the same,

drop table #subatable
select id, rating, dat,month(dat) as mont
into #subatable from
(
select id,rating,row_number() over( partition by id,month(dat) order by auditrecord desc)
as rownum,dat
,month(dat) as mont
from venkat1
)t
where rownum=1
select * from #subatable

Now, a simple row to column conversion with input parameter as month.


Below is the query for the same,

select distinct a.id, month1 =(select rating from #subatable where mont=7 and id=a.id),
month2 =(select rating from #subatable where mont=8 and id=a.id)
from #subatable a

Happy Learning!!!

Thanks and Regards,

Venkatesan Prabu .J

User defined tables in sql server

User tables in SQL Server:
How to get the user created tables in SQL?
sys.tables view:
sys.tablev iew list down all the tables available in the database. The type column is used to pick or differentiate a table between user define one or system related one.

Below is the query to fetch User created tables in SQL Server,
select * from sys.tables where type ='U'

Thanks and Regards,
Venkatesan Prabu .J

13.5.09

Strange error in dynamic queries in SQL Server

Dynamic query error in SQL Server:

Another strange error while executing the dynamic query in SQL Server
Below is the query used,

drop table Customers
CREATE TABLE Customers
(
Cus_ID int PRIMARY KEY ,
Cus_Name varchar(30) NOT NULL,
Cus_City varchar(30) NOT NULL,
Cus_Country varchar(30) NOT NULL
)
insert into customers values(1,'venkat','dpi','india')
DECLARE @SQL varchar(1000)
declare @cus_name varchar(1000)
declare @Cus_City varchar(1000)
declare @Cus_Country varchar(1000)
set @Cus_Name ='venkat'
SET @SQL = 'SELECT Cus_Name, Cus_City, Cus_Country FROM Customers '
SET @SQL = @SQL + 'WHERE '
SET @SQL = @SQL + 'Cus_Name = ' + @Cus_Name

EXEC(@SQL)


I got a strange SQL Server error, Invalid column name 'venkat'. But am giving column value, why it's throwing column name error. Strange !!!!

To over come this error, we need to change the value given in the set statement.

drop table Customers
CREATE TABLE Customers
(
Cus_ID int PRIMARY KEY ,
Cus_Name varchar(30) NOT NULL,
Cus_City varchar(30) NOT NULL,
Cus_Country varchar(30) NOT NULL
)
insert into customers values(1,'venkat','dpi','india')
DECLARE @SQL varchar(1000)
declare @cus_name varchar(1000)
declare @Cus_City varchar(1000)
declare @Cus_Country varchar(1000)
set @Cus_Name ='''venkat'''
SET @SQL = 'SELECT Cus_Name, Cus_City, Cus_Country FROM Customers '
SET @SQL = @SQL + 'WHERE '
SET @SQL = @SQL + 'Cus_Name = ' + @Cus_Name

EXEC(@SQL)


Thanks and Regards,

Venkatesan Prabu .J

Strange error message in sql server -Dynamic query execution

Dynamic query in SQL Server
I had a chance to execute dynamic query in sql server.

1. Declared a variable
2. Assign a query to the variable inside single quotes
3. Execute the variable.


On executing the statements, I got a strange query "Could not find stored procedure 'variable string' ". I am bit worried to see this error.
Solution:
Execute statement should have variable inside the brackets .

Why microsoft have given such a strange error message. They are not specifying the error message properly. Let me post this to Microsoft.

Thanks and Regards,
Venkatesan Prabu .J

12.5.09

Variable as column name in sql server


Problem description:

Am trying to assign the variable value as the column name in the table output.
To overcome this issue, we need to use dynamic queries. Initially, I have assigned the value
into a variable and used in the select statement.

Thanks and Regards,
Venkatesan Prabu .J

Group by month in SQL Server

Group by month's in SQL server:

Lets see some peculiar example, I need to group the data based on the id and grouped by month. The data is located in the rows and I need to populate the data in columns. How to achieve it?

DROP TABLE SAMPLE
create table sample(id int, BusId varchar(5), amt1 decimal(10,2), amnt2 decimal(10,2), dat datetime)
insert into sample values(1, 'A1234', 100,200,'2008-12-03')
insert into sample values(2, 'A1234', 200,200,'2008-12-30')
insert into sample values(3, 'A1234', 300,200,'2008-12-31')
insert into sample values(4, 'A1234', 400,200,'2009-01-03')
insert into sample values(5, 'A1234', 500,200,'2009-01-22')
insert into sample values(6, 'A1234', 600,200,'2009-02-13')
select * from sample




select BUSID,AMT1,AMNT2,CONVERT(VARCHAR(100),MONTH(DAT))+' '+CONVERT(VARCHAR(100),YEAR(DAT)) AS VAL from sample


SELECT BUSID, SUM(AMT1) as AMOUNT1,SUM(AMNT2) AS AMOUNT2 ,DAT1 FROM
(
select BUSID,AMT1 ,AMNT2,CONVERT(CHAR(4), dat, 100) + CONVERT(CHAR(4), dat, 120) AS DAT1 from sample
)T
GROUP BY DAT1,BUSID




Thanks and Regards,

Venkatesan Prabu .J

Datetime format in SQL Server

Format in date:

We can format the dates using convert statement in sql server.

In the below example, am trying to fetch the months available in the table. Considering am having 10 rows with different dates. On the high level, I need to fetch the available months in the table records

DROP TABLE SAMPLE
create table sample(id int, BusId varchar(5), amt1 decimal(10,2), amnt2 decimal(10,2), dat datetime)
insert into sample values(1, 'A1234', 100,200,'2008-12-03')
insert into sample values(2, 'A1234', 200,200,'2008-12-30')
insert into sample values(3, 'A1234', 300,200,'2008-12-31')
insert into sample values(4, 'A1234', 400,200,'2009-01-03')
insert into sample values(5, 'A1234', 500,200,'2009-01-22')
insert into sample values(6, 'A1234', 600,200,'2009-02-13')
select * from sample
select * from
(
select CONVERT(CHAR(4), dat, 100) + CONVERT(CHAR(4), dat, 120) AS DAT1 from sample
)t
group by dat1

Thanks and Regards,
Venkatesan Prabu .J

5.5.09

Simple logic on rows to columns in sql server

Problem statement :
Am having data in rows and I need to customize into columns.
How to group the data in different format?

create table venkatTable(subject varchar(10),marks int,Gender varchar(10))
insert into venkatTable values('Maths',50,'F')
insert into venkatTable values('Maths',20,'M')
insert into venkatTable values('English',50,'F')
insert into venkatTable values('English',30,'M')
insert into venkatTable values('Physics',50,'F')
insert into venkatTable values('Physics',70,'M')
select * from venkatTable


select distinct a.subject,M =
(select marks from venkattable where subject=a.subject and gender='M')
,F= (select marks from venkattable where subject=a.subject and gender='F')
from venkattable a

Thanks and Regards,
Venkatesan Prabu .J

Row data as a comma seperated string

Problem statment:
Am having lot of records in my table. I need to take the rows and converted in to a comma seperated string. Is it possible?

create table venkatTable(subject varchar(10),marks int,Gender varchar(10))
insert into venkatTable values('Maths',50,'F')
insert into venkatTable values('Maths',20,'M')
insert into venkatTable values('English',50,'F')
insert into venkatTable values('English',30,'M')
insert into venkatTable values('Physics',50,'F')
insert into venkatTable values('Physics',70,'M')

declare @val varchar(100)
set @val=''
select @val=@val+','+subject from venkatTable
print substring(@val,2,len(@val))


Thanks and Regards,
Venkatesan Prabu .J

SQL Server Login error

Usually while accessing the serer from remote machine, we used to get the below error,
"An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 2)"

Reason for this error:
SQL Server is configured to use it locally, remote machines can't access the server.
Steps to rectify it:
start->programs->MS sql server->configuration tool->sql server surface area configuration -> surface area and configuration for service and connection->
sqlexpress->database engine-> remote connections-> activate local and remote connections->select using both tcp/ip ->apply

After this step, restart the database server. This error will disappear

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