Monday, August 24, 2009
SQL Verify that the stored procedure does not already exist.
DROP PROCEDURE usp_GetErrorInfo;
SQL CATCH Block System Functions
-- SET XACT_ABORT ON will cause the transaction to be uncommittable when the constraint violation occurs.
Sunday, August 23, 2009
SQL Error Handling (Try, Catch)
BEGIN TRY
Try Statement 1
Try Statement 2
...
Try Statement M
END TRY
BEGIN CATCH
Catch Statement 1
Catch Statement 2
...
Catch Statement N
END CATCH
Example 1 : Simple TRY…CATCH without RAISERROR function
BEGIN TRY
DECLARE @MyInt INT;
– Following statement will create Devide by Zero Error
SET @MyInt = 1/0;
END TRY
BEGIN CATCH
SELECT ‘Divide by zero error encountered.’ ErrorMessage
END CATCH;
GO
ResultSet:
ErrorMessage
Divide by zero error encountered.
Example 2 : Simple TRY…CATCH with RAISERROR function
BEGIN TRY
DECLARE @MyInt INT;
– Following statement will create Devide by Zero Error
SET @MyInt = 1/0;
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
SELECT @ErrorMessage = ERROR_MESSAGE();
RAISERROR (@ErrorMessage, 16, 1);
END CATCH;
GO
ResultSet:
Msg 50000, Level 16, State 1, Line 9
Divide by zero error encountered.
Example 3 :
CREATE PROCEDURE DeleteEmployee ( @EmployeeID int )
AS
BEGIN TRANSACTION -- Start the transaction
-- Delete the Employee's phone numbers
DELETE FROM EmployeePhoneNumbers WHERE EmployeeID = @EmployeeID
-- Delete the Employee record
DELETE FROM Employees WHERE EmployeeID = @EmployeeID
-- See if there is an error
IF @@ERROR <> 0
-- There's an error b/c @ERROR is not 0, rollback
ROLLBACK
ELSE
COMMIT -- Success! Commit the transaction
Thursday, August 20, 2009
SQL
SQL Column and Row check to get date between
set @StDt='2009-06-17 11:00:00.000'
set @EdDt= '2009-06-18 12:30:00.000'
select * from Notification N
where
(N.Start_DateTime between @StDt and @EdDt
or N.End_DateTime between @StDt and @EdDt
or @StDt between N.Start_DateTime and N.End_DateTime
or @EdDt between N.Start_DateTime and N.End_DateTime)
SQL Get Duplicate Records(Pairs of Duplicate Row) in table
from emp
group by Ename
having count(*) > 1
select sal,Ename,count(*)
from emp
group by sal,Ename
having count(*) > 1
select sal,Ename
from emp
group by sal,Ename
having count(*) > 1
Return all pairs of city IDs that have the same city name
select * from emp
select c1.empno, c2.empno, c1.Ename
from emp c1, emp c2
where c1.empno ename = c2.Ename
Delete Duplicate Records – Rows
Example:1
DELETE
FROM emp
WHERE Empno NOT IN (SELECT MAX(Empno)FROM empGROUP BY ename)
Example:2
DELETE
FROM emp
WHERE EXISTS (
SELECT * FROM emp AS b
WHERE
b.[ename] = emp.[ename]
--AND b.[col2] = emp.[col2]
--AND b.[col3] = emp.[col3]
GROUP BY b.[ename]--, b.[col2], b.[col3]
HAVING emp.[Empno] > MIN(b.[Empno]
)
SQL Declare, If-esle, cast
set @x='hai'
if(@x<>'hmai')//<>,=,>,<,>=.<=,!=
begin
print(@x)
end
declare @x char(10)
set @x='hai'
if(@x is not null)
begin
print(@x)
end
declare @x char(10)
set @x='hai'
if((@x<>'hai1')or(@x<>'hai2'))//or,and
begin
print(@x)
end
else
begin
print('else')
end
declare @x char(200)
set @x='select * from prgm'
Exec(@x)
Declare @ValidRule as varchar(10)
Set @ValidRule = 'False'
Declare @a as varchar(10)
Declare @prg as varchar(10)
Set @prg=null
Set @a=select * from program P where prg_id=isnull('+cast(@prg as varchar)+',P.prg) )//if @prg is null P.prg is assign to
Tuesday, August 18, 2009
SQL Begin, Rollback & Commit Transaction
BEGIN TRAN;
select * from tbl1;
DELETE FROM tbl1 where age=32 OR age=79;
select * from tbl1;
ROLLBACK TRAN;
select * from tbl1;
BEGIN TRAN;
select * from tbl1;
DELETE FROM tbl1 where age=32 OR age=79;
select * from tbl1;
COMMIT TRAN;
select * from tbl1;
SQL String Functions
select * from tbl1;
SELECT Fname,LEFT(Fname, 2) FROM tbl1;
SELECT Fname,RIGHT(Fname, 2) FROM tbl1;
SELECT Fname,LEN(Fname) FROM tbl1;
SELECT Fname,SUBSTRING(Fname, 2, 4) FROM tbl1;
SELECT Fname,PATINDEX('%na%', Fname)FROM tbl1;
SELECT Fname+city FROM tbl1;
SELECT Fname,REPLACE(Fname, 'a','') FROM tbl1;
INSERT INTO tbl1(Fname,age,city) SELECT Fname,age+12,city FROM tbl1;--we can select from other table also
SQL Case, Trim Statement
SELECT sno,total,average
, CASE WHEN average 50 THEN 'Fail'
WHEN average>50 THEN 'Pass'
ELSE 'Not Eligible'
END as result
FROM tbl3;
SELECT sno,average,average%2 FROM tbl3;
Example:2
case when ltrim(rtrim(a.Program)) = ltrim(rtrim(pgm.prgm_name))
and ltrim(rtrim(a.Partner)) = ltrim(rtrim(Partner.Partner_Name))
and ltrim(rtrim(a.Measure)) = ltrim(rtrim(msre.Msre_Name))
then 1
else 0
end Flag
SQL View Statement
SQL IN clause - Copy tables into another database
The IN clause can be used to copy tables into another database:
SELECT Persons.* INTO Persons IN 'Backup.mdb' FROM Persons
create database sampleBackup;
SELECT tbl3.* INTO tbl3 IN 'sampleBackup.mdb' FROM tbl3;
DROP DATABASE sampleBackup;
use sample;
SQL Select INTO Statement
SQL Group By/ Having
SELECT SUM(m1) FROM tbl3;
SELECT SUM(m1) FROM tbl3 GROUP BY sno;
SELECT SUM(m1) as Sum_Of_m1 FROM tbl3 GROUP BY sno;
SELECT sno,SUM(m1),avg(m1) FROM tbl3 GROUP BY sno;
SELECT m1,SUM(m1) FROM tbl3 GROUP BY sno;/*invalid*/
Aggregate/ Scalar functions
create table tbl3 (sno varchar(10),m1 int,m2 int,total int,average int);
insert into tbl3 (sno,m1,m2) values ('1',10,20);
insert into tbl3 (sno,m1,m2) values ('2',30,40);
insert into tbl3 (sno,m1,m2) values ('3',50,60);
select * from tbl3;
UPDATE tbl3 SET total = m1+m2, average=total/2;
Aggregate functions
Aggregate functions operate against a collection of values, but return a single value.
Note: If used among many other expressions in the item list of a SELECT statement, the SELECT must have a GROUP BY clause!!
SELECT AVG(m1) FROM tbl3 WHERE m1>20;
SELECT COUNT(sno) FROM tbl3;
SELECT COUNT(*) FROM tbl3;
insert into tbl3 (sno,m1,m2) values ('3',5,60);
SELECT COUNT(DISTINCT sno) FROM tbl3;
/*SELECT FIRST(column) AS [expression] FROM table*/
SELECT FIRST(sno) AS lowest_m1 FROM tbl3 ORDER BY m1;
/*SELECT LAST(column) AS [expression] FROM table*/
SELECT LAST(m1) AS highest_m1 FROM tbl3 ORDER BY m1;
SELECT MAX(m1) FROM tbl3;
SELECT MIN(m1) FROM tbl3;
SELECT SUM(m1) FROM tbl3;
Scalar functions
Scalar functions operate against a single value, and return a single value based on the input value.
SQL Select Maximun/ Minimun value in table
select * from
(select row_number() over(order by sal desc) id, * from emp ) a
where a.id =2 //Where 2 is second Maximum
select * from tblStudent a where &n-1=(select count(*) from tblStudent b where a.mark
(OR)
select * from tblStudent a where &n=(select count(*) from tblStudent b where a.mark<=b.mark)
Example
select * from tblStudent a where 2=(select count(*) from tblStudent b where a.mark<=b.mark)
//Where 2 is second Maximum
Nth Minimum
select * from
(select row_number() over(order by sal asc) id, * from emp ) a
where a.id =2 //Where 2 is second Minimum
select * from tblStudent a where &n-1=(select count(*) from tblStudent b where a.mark>b.mark)
(OR)
select * from tblStudent a where &n=(select count(*) from tblStudent b where a.mark>=b.mark)
Example
select * from tblStudent a where 2=(select count(*) from tblStudent b where a.mark>=b.mark)
//Where 2 is second Minimum
2nd Maximum
Select max(mark) From tblStudent where mark NOT IN (Select max(mark) From tblStudent)
Select top(1) From tblStudent where mark NOT IN (Select max(mark) From tblStudent) Order By mark desc
Select top(1) From tblStudent where mark IN (Select max(mark) From tblStudent where mark NOT IN (Select max(mark) From tblStudent))
SQL To get Serial Number for each record
select * from #tmptable
drop table #tmptable
SQL Truncate Vs Delete
2. We can't use WHERE clause in Truncate
3. Truncate statement will not fire the trigger.
4. While using truncate statement the table identity column counter reset to 0. But in the case of delete it will maintain the old counter value.
5. You can't use truncate if the table referenced by a foreign key constraint. 6. Both we can Rollback.
CREATE TABLE TruncateTest ( id int )
INSERT INTO TruncateTest VALUES(1)
SELECT * FROM TruncateTest
BEGIN TRANSACTION;
TRUNCATE TABLE TruncateTest
ROLLBACK TRANSACTION
SELECT * FROM TruncateTest
DROP TABLE TruncateTest
SQL Rename Command
RENAME old_table_name To new_table_name;
For Example:
To change the name of the table employee to my_employee, the query would be like
RENAME employee TO my_emloyee;
SQL Alter/ Modify Table
can use an ALTER TABLE command to add, modify, or drop (remove) columns or constraints.
An ALTER TABLE command has the following syntax
- ADD COLUMN field type[(size)] [NOT NULL] [CONSTRAINT constraint]
- ADD CONSTRAINT multifield_constraint
- ALTER COLUMN field type[(size)]
- DROP COLUMN field
- DROP CONSTRAINT constraint
Example
ALTER TABLE table_name MODIFY column_name datatype;
For Example: To modify the column salary in the employee
table, the query would be like
ALTER TABLE employee MODIFY salary number(15,2);//this is error in sql server
(or)
ALTER TABLE employee ALTER COLUMN salary number(15,2);)//this is correct in sql server
SQL Indexes
SQL Union/ Union All Query
SELECT Fname FROM tbl1SELECT Fname FROM tbl2;
SELECT Fname FROM tbl1
UNION
SELECT Fname FROM tbl2;
SELECT Fname FROM tbl1 UNION ALL SELECT Fname FROM tbl2;
SQL Join Query
insert into tbl2 values ('AFname','Aaddress');
insert into tbl2 values ('BFname','Baddress');
insert into tbl2 values ('AFname','AAaddress');
insert into tbl2 values ('DFname','DAaddress');
JOIN
SELECT tbl1.Fname,tbl1.age,tbl2.address FROM tbl1,tbl2;
SELECT tbl1.Fname,tbl1.age,tbl2.address FROM tbl1,tbl2 WHERE tbl1.Fname=tbl2.Fname; SELECT t1.Fname,t1.age,t2.address FROM tbl1 AS t1,tbl2 AS t2;
SELECT t1.Fname,t1.age,t2.address FROM tbl1 AS t1,tbl2 AS t2 WHERE t1.Fname=t2.Fname;
INNER JOIN
SELECT field1, field2, field3
FROM first_table
INNER JOIN second_table ON first_table.keyfield = second_table.foreign_keyfield
FROM tbl1
INNER JOIN tbl2 ON tbl1.Fname=tbl2.Fname;
SELECT * FROM tbl1 INNER JOIN tbl2 ON tbl1.Fname=tbl2.Fname;
LEFT JOIN
SELECT field1, field2, field3
FROM first_table
LEFT JOIN second_table ON first_table.keyfield = second_table.foreign_keyfield
select * from tbl2;
SELECT tbl1.Fname,age,city,tbl2.address
FROM tbl1
LEFT JOIN tbl2 ON tbl1.Fname=tbl2.Fname;
SELECT * FROM tbl1 LEFT JOIN tbl2 ON tbl1.Fname=tbl2.Fname;
RIGHT JOIN
SELECT field1, field2, field3
FROM first_table
RIGHT JOIN second_table ON first_table.keyfield = second_table.foreign_keyfield
select * from tbl1;
select * from tbl2;
SELECT tbl1.Fname,age,city,tbl2.address
FROM tbl1
RIGHT JOIN tbl2 ON tbl1.Fname=tbl2.Fname;
SELECT * FROM tbl1 RIGHT JOIN tbl2 ON tbl1.Fname=tbl2.Fname;
SELECT * FROM tbl1 RIGHT JOIN tbl2 ON tbl1.Fname=tbl2.Fname WHERE tbl1.city='Acity';
SQL Help Query
Returning information about a single object. The following example displays information about the Contact table. EXEC sp_help Contact;
The following example reports on the types of indexes on the Customer table.
EXEC sp_helpindex 'Customer';
EXEC sp_helplogins 'sa'
Who are the users for database sp_who2
For get Stored Procedure Query sp_helptext ProcedureName
Basic SQL Query
/*DROP DATABASE database_name;*/
DROP DATABASE sample;
use sample;
create table tbl1 (Fname varchar(10),age int,city varchar(5));
insert into tbl1 values ('AFname',20,'Acity');
insert into tbl1 values ('BFname',20,'Bcity');
insert into tbl1 values ('BFname',20,'Bcity');
INSERT INTO tbl1 (Fname, age) VALUES ('CFname', 67);
select * from tbl1;
truncate table tbl1;
drop table tbl1;
select * from tbl1;
select DISTINCT Fname,age,city from tbl1;
SELECT * FROM tbl1 WHERE Fname LIKE 'a%';/*Fname start with an 'a'*/
SELECT * FROM tbl1 WHERE Fname LIKE '%e';/*Fname end with an 'e'*/
SELECT * FROM tbl1 WHERE Fname LIKE '%bn%';/*Fnames that contain the pattern 'bn'*/
UPDATE
UPDATE tbl1 SET Fname = 'CCFname' WHERE Fname = 'CFname';
UPDATE tbl1 SET Fname = 'CFname',age=7,city='Ccity' WHERE Fname = 'CCFname';
DELETE
DELETE FROM tbl1 WHERE Fname = 'BFname';
DELETE FROM tbl1;
DELETE * FROM tbl1;--Incorrect syntax near '*'.
ORDER BY
SELECT * FROM tbl1 ORDER BY Fname;
SELECT * FROM tbl1 ORDER BY Fname ASC;
SELECT * FROM tbl1 ORDER BY Fname, age;
SELECT * FROM tbl1 ORDER BY Fname DESC;
AND/ OR
SELECT * FROM tbl1 WHERE Fname='AFname' AND age<21;>
SELECT * FROM tbl1 WHERE Fname='AFname' OR age<21;>
IN
SELECT * FROM tbl1 WHERE (Fname='AFname' AND age<21) city="'Ccity';">
SELECT * FROM tbl1 WHERE Fname NOT IN ('AFname','BFname');
BETWEEN
SELECT * FROM tbl1 WHERE Fname BETWEEN 'AFname' AND 'BFname';
SELECT * FROM tbl1 WHERE age BETWEEN 10 AND 20;
SELECT * FROM tbl1 WHERE age NOT BETWEEN 10 AND 20;
Alias Name
SELECT Fname AS Name FROM tbl1;//Column Fname Alias
SELECT Fname FROM tbl1 AS t1;//Table Fname Alias
SELECT t1.Fname,t1.age FROM tbl1 AS t1;