Thursday, 16 June 2011

SQL: User ERROR orUSER STORED PROCEDURE

--Create a table TEST1 having 2 field T_ID,T_NAME
CREATE TABLE TEST1
(
T_ID INT IDENTITY(1,1) PRIMARY KEY,
T_NAME VARCHAR(25)
)


--Create another table TEST2_DEPEND having 2 field TD_ID,TD_ADDRESS
GO
CREATE TABLE TEST2_DEPEND
(
TD_ID INT FOREIGN KEY REFERENCES TEST1(T_ID),
TD_ADDRESS VARCHAR(25)
)
GO

--Insert into TEST1 Values
GO
INSERT INTO TEST1 VALUES ('Manoj')
GO
INSERT INTO TEST1 VALUES ('Kumar')
GO
INSERT INTO TEST1 VALUES ('Bardhan')
GO

--User Stored Procedure For Insert/Delete (Pass 'D' for Delete,'I' for Insert)
--This Below defined procedure raiserror user defined error to user when some Error
--like Foreign Key Violation,Duplicate Key Entry (Primary key) or any other errors.
--I have first get the Error No. and then check the Error and Error No given in sys.messages message_id,language_id.
--Language id is defined in sys.syslanguages msglangid for us_english language(1033).ERROR_NUMBER() function is used
--to get the Error No. from the current session.

--I have used SQL Transaction for better accuracy of data in database .I used Begin Tran,ROllback Tran,Commit for
--implementing TCL structure in SQL Database.If any error occurs during execution the wrong data may not violate the
--database implemented rules.

GO
CREATE PROC USP_TEST1
(
@OP_TYP VARCHAR(3),
@ID INT,
@ADDRESS VARCHAR(30)=NULL
)
AS
BEGIN TRY
BEGIN TRAN
IF @OP_TYP='I'
BEGIN
INSERT INTO TEST1 VALUES(@ADDRESS)
END
ELSE IF @OP_TYP='D'
BEGIN
DELETE FROM TEST1 WHERE T_ID=@ID
END
COMMIT
END TRY
BEGIN CATCH
DECLARE @TMP VARCHAR(MAX)
SET @TMP=ERROR_NUMBER();
IF @TMP=547
BEGIN
--RAISERROR raise Error For user (If Any)
RAISERROR('Cannot Delete! Value Dependency (Foreign key)??? ',16,1)
--Transaction Rollback for keeping only Old Data
ROLLBACK TRAN
END
ELSE IF @TMP=2627
BEGIN
RAISERROR('Cannot Insert! Cannot Insert Duplicate Value ???',16,1)
--Transaction Rollback for keeping only Old Data
ROLLBACK TRAN
END
ELSE
BEGIN
--RAISERROR raise Error For user (If Any)
RAISERROR('Some Error in DataBase??',16,1)
--Transaction Rollback for keeping only Old Data
ROLLBACK TRAN
END
END CATCH
GO



--Insert value Into Foreign key Table Value
INSERT INTO TEST2_DEPEND VALUES(2,'Bhubaneswar')

--Execute the Procedure For Delete From Primary Table(D=Delete,I=insert)
EXEC USP_TEST1 'D',2

--Expected Output Error

(0 row(s) affected)
Msg 50000, Level 16, State 1, Procedure USP_TEST1, Line 26
Cannot Delete! Value Dependency (Foreign key)???




I have used all this type of error handling error for the developers which will not hamper the frontend developer to handle error from
application frontend.For better knowledge about Errors & Languages in SQL Follow the below lines.


SELECT * FROM SYS.MESSAGES

SELECT * FROM SYS.SYSLANGUAGES


Posted By:-javadevelopersguide
Link:-http://javadevelopersguide.blogspot.com

SQL: Adding IDENITY property to Existing Column

--Adding IDENITY property to Existing Column
--Steps to Add Identity
1.Add new Column with IDENTITY
2.Drop Constraint (if Any)
3.Drop the Old Column
4.Rename the New Column with Old Column Name


--Existing Table
CREATE TABLE Employee
(
Emp_Id INT PRIMARY KEY,
Emp_Name VARCHAR(100)
)

--1St Add a New Column with Identity
ALTER TABLE Employee
ADD EmpNew_ID INT IDENTITY (1,1)


--2Nd Drop The Primary Key Constraints(if Primary key is exist)
ALTER TABLE Employee
DROP CONSTRAINT PK__Employee__262359AB07020F21

--3Rd Drop the Old ID from Table
ALTER TABLE Employee
DROP COLUMN Emp_ID

--4Th Rename the New Column with OLD Column Name
SP_RENAME 'Employee.EmpNew_ID','Emp_Id','COLUMN'



--Now enjoy the Column & Table with new Flavour of IDENTITY.Really I had so much curisity to know when I got this from one
--of my friend as Co-worker.Firstly I though that it is so simple as we alter any column of any table but after 20-30 min.I
--realize that this is the proper way for accomplish the Task.But , be sure that that table donot have any data and always consider
--for Primary key ,if necessary first drop the Primary key the proceed.May be the cadinal position of the changed column.



--Show the Table with New Form
SELECT * FROM TEST_TABLE


















--Posted By: javadevelopersguide
--Link:-http://javadevelopersguide.blogspot.com

Wednesday, 15 June 2011

SQL: Rename Column or Tables,Use of SP_RENAME

--Rename a Column Name replacing Old_Name

EXEC SP_RENAME 'TABLE_NAME.COLUMN_NAME','COLUMN_NAME','COLUMN'

OR

SP_RENAME 'TABLE_NAME.COLUMN_NAME','COLUMN_NAME','COLUMN'




ALTER TABLE Employee
ALTER COLUMN EMP_NAME VARCHAR(100)



--Renaming a table

EXEC SP_RENAME 'Employee', 'New_employee'

OR

SP_RENAME 'Employee', 'New_employee'




SP_RENAME, Procedure Changes the name of a user-created object in the current database.


Remarks:

Changing any part of an object name can break scripts and stored procedures.
I recommend you do not use this statement to rename stored procedures, triggers,
user-defined functions, or views; instead, drop the object and re-create it with the
new name.

To rename objects, columns, and indexes, requires ALTER permission on the object.
To rename user types, requires CONTROL permission on the type. To rename a database,
requires membership in the sysadmin or dbcreator fixed server roles .



Posted By:- javadevelopersguide
Link: http://javadevelopersguide.blogspot.com

SQL: Fetching Record One-by-One without using Cursor

--Fetching Record One-by-One without using Cursor


DECLARE @EMP_ID CHAR( 11 )
SET ROWCOUNT 0
SELECT * INTO #MYTEMP FROM Employee

SET ROWCOUNT 1

SELECT @EMP_ID = EMP_ID FROM #Employee

WHILE @@ROWCOUNT <> 0
BEGIN
SET ROWCOUNT 0
SELECT * FROM #MYTEMP WHERE EMP_ID = @EMP_ID
DELETE #MYTEMP WHERE EMP_ID = @EMP_ID

SET ROWCOUNT 1
--Set one id to @EMP_ID from #MYTEMP
SELECT @EMP_ID= EMP_ID FROM #MYTEMP
END
SET ROWCOUNT 0



Remarks:

Always avoid to use cursor due to slower execution.In the above query Cursor can be
replaced by above way.I used a tempory table and Rowcount property.When ROWCOUNT is 0 ,the sql statement
can execute with any number of record operation,But when ROWCOUNT is 1
at that time the the sql statement can work with only one Record.So I have used this for my
requirement ,without using CURSOR record fetching One-By-One is possible.




Posted By:javadevelopersguide
Link:-http://javadevelopersguide.blogspot.com

Monday, 13 June 2011

SQL:Disable Or Enable a Trigger

Triggers are enabled by default when they are created. Disabling a trigger does not drop it. The trigger still exists as an object in the current database. However, the trigger does not fire when any Transact-SQL statements on which it was programmed are executed. Triggers can be re-enabled by using ENABLE TRIGGER. DML triggers defined on tables can be also be disabled or enabled by using ALTER TABLE.


Purpose of the following Trigger
---------------------------------
--AVOIDE TO DROP TABLES FROM DATABASE

USE Test_Manoj
Go

CREATE TRIGGER TRG_DB_SAFTY
ON DATABASE
FOR DROP_TABLE
AS
RAISERROR('DROP CANNOT POSSIBLE,PLEASE CONTACT ADMIN..',16,1)
ROLLBACK ;

After creation of trigger any point of time a trigger can be disable or enable by the user.For Disable a trigger(de-activate) DISABLE keyword is used as follows:-

--Disable Trigger on Database

USE Test_Manoj
Go
disable TRIGGER TRG_DB_SAFTY on database

For Enable a trigger on Database,any other object we need ENABLE keyword as follows:-


--Enable trigger on Database

USE Test_Manoj
Go
ENABLE TRIGGER TRG_DB_SAFTY on database



Disabling all triggers

----------------------------
--Disable all triggers on all server

USE Test_Manoj
Go
DISABLE Trigger ALL ON ALL SERVER

OR

--Disable all triggers in Database

USE Test_Manoj
Go
DISABLE Trigger ALL ON DATABASE
Go


Disable Trigger on Table
---------------------------------
USE Test_Manoj
Go
DISABLE Trigger ALL ON DBO.MY_EMP
Go





Posted By:-javadevelopersguide
Link:-http://javadevelopersguide.blogspot.com

SQL: Function for finding Number of Column in a Given Table

Below a function which can be used to find the no.of column in a specified Table.This function returns an INT(Scalar Value).This Type of function is known as scalar valued function.


--FUNCTION FOR FINDING NO OF COLUMN FROM GIVEN TABLE

--Create a function with Table_Name as Parameter
CREATE FUNCTION FUN_COL_COUNT(@T_NAME VARCHAR(50))
RETURNS INT
AS
BEGIN
DECLARE @CNT INT
SELECT @CNT=MAX(ORDINAL_POSITION) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=@T_NAME
RETURN @CNT
END

--Run the Function

SELECT DBO.FUN_COL_COUNT('Table_name')

This above statement return the no.of column in the Table_name .Here DBO represents DataBase Object(Schema).More about Schema read some other articles/Posts.


Here Information schema views provide an internal, system table-independent view of the SQL Server metadata. Information schema views enable applications to work correctly although significant changes have been made to the underlying system tables. The information schema views included in SQL Server comply with the ISO standard definition for the INFORMATION_SCHEMA.

Posted By: javadevelopersguide
Link:-http://javadevelopersguide.blogspot.com