Wednesday, 25 January 2012

STORED PROCEDURE | SQL Server Interview Questions

1. What is Stored procedure?
A stored procedure is a set of Structured Query Language (SQL) statements that you assign a name to and store in a database in compiled form so that you can share it between a number of programs.
  •  They allow modular programming.
  •  They allow faster execution.
  •  They can reduce network traffic.
  •  They can be used as a security mechanism.
2. What are the different types of Storage Procedure?
  1.  Temporary Stored Procedures - SQL Server supports two types of temporary procedures: local and global. A local temporary procedure is visible only to the connection that created it. A global temporary procedure is available to all connections. Local temporary procedures are automatically dropped at the end of the current session. Global temporary procedures are dropped at the end of the last session using the procedure. Usually, this is when the session that created the procedure ends. Temporary procedures named with # and ## can be created by any user.
  2.   System stored procedures- are created and stored in the master database and have the sp_ prefix.(or xp_) System stored procedures can be executed from any database without having to qualify the stored procedure name fully using the database name master. (If any user-created stored procedure has the same name as a system stored procedure, the user-created stored procedure will never be executed.)
  3.  Automatically Executing Stored Procedures - One or more stored procedures can execute automatically when SQL Server starts. The stored procedures must be created by the system administrator and executed under the sysadmin fixed server role as a background process. The procedure(s) cannot have any input parameters.
  4.  User stored procedure

3. How do I mark the stored procedure to automatic execution?
You can use the sp_procoption system stored procedure to mark the stored procedure to automatic execution when the SQL Server will start. Only objects in the master database owned by dbo can have the startup setting changed and this option is restricted to objects that have no parameters.
USE master
(EXEC sp_procoption 'indRebuild', 'startup', 'true')

4. How will know whether the SQL statements are executed?

When used in a stored procedure, the RETURN statement can specify an integer value to return to the calling application, batch, or procedure. If no value is specified on RETURN, a stored procedure returns the value 0. The stored procedures return a value of 0 when no errors were encountered. Any nonzero value indicates an error occurred.

5. Why one should not prefix user stored procedures with sp_?
It is strongly recommended that you do not create any stored procedures using sp_ as a prefix. SQL Server always looks for a stored procedure beginning with sp_ in this order:
  •     The stored procedure in the master database.
  •     The stored procedure based on any qualifiers provided (database name or owner).
  •     The stored procedure using dbo as the owner, if one is not specified.
Therefore, although the user-created stored procedure prefixed with sp_ may exist in the current database, the master database is always checked first, even if the stored procedure is qualified with the database name.

6. What can cause a Stored procedure execution plan to become invalidated and/or fall out of cache?
  •   Server restart
  •   Plan is aged out due to low use
  •   DBCC FREEPROCCACHE (sometime desired to force it)
7. When do one need to recompile stored procedure?
if a new index is added from which the stored procedure might benefit, optimization does not automatically happen (until the next time the stored procedure is run after SQL Server is restarted).

8. SQL Server provides three ways to recompile a stored procedure:
  • The sp_recompile system stored procedure forces a recompile of a stored procedure the next time it is run.
  • Creating a stored procedure that specifies the WITH RECOMPILE option in its definition indicates that SQL Server does not cache a plan for this stored procedure; the stored procedure is recompiled each time it is executed. Use the WITH RECOMPILE option when stored procedures take parameters whose values differ widely between executions of the stored procedure, resulting in different execution plans to be created each time. Use of this option is uncommon, and causes the stored procedure to execute more slowly because the stored procedure must be recompiled each time it is executed.
  • You can force the stored procedure to be recompiled by specifying the WITH RECOMPILE option when you execute the stored procedure. Use this option only if the parameter you are supplying is atypical or if the data has significantly changed since the stored procedure was created.

9. How to find out which stored procedure is recompiling? How to stop stored procedures from recompiling?
10. I have Two Stored Procedures SP1 and SP2 as given below. How the Transaction works, whether SP2 Transaction succeeds or fails?

CREATE PROCEDURE SP1 AS
BEGIN TRAN
INSERT INTO MARKS (SID,MARK,CID) VALUES (5,6,3)
EXEC SP2
ROLLBACK
GO

CREATE PROCEDURE SP2 AS
BEGIN TRAN
INSERT INTO MARKS (SID,MARK,CID) VALUES (100,100,103)
commit tran
GO
Both will get roll backed.
CREATE PROCEDURE SP1 AS
BEGIN TRAN
    INSERT INTO MARKS (SID,MARK,CID) VALUES (5,6,3)
    BEGIN TRAN
        INSERT INTO STUDENT (SID,NAME1) VALUES (1,'SA')
    commit tran
ROLLBACK TRAN
GO
Both will get roll backed.

11. How will you handle Errors in Sql Stored Procedure?
INSERT NonFatal VALUES (@Column2)
IF @@ERROR <>0
 BEGIN
  PRINT 'Error Occured'
 END
http://www.sqlteam.com/item.asp?ItemID=2463

12. How will you raise an error in sql?
RAISERROR - Returns a user-defined error message and sets a system flag to record that an error has occurred. Using RAISERROR, the client can either retrieve an entry from the sysmessages table or build a message dynamically with user-specified severity and state information. After the message is defined it is sent back to the client as a server error message.
I have a stored procedure like
commit tran
create table a()
insert into table b
--
--
rollback tran
what will be the result? Is table created? data will be inserted in table b?

13. How you will return XML from Stored Procedure?
You use the FOR XML clause of the SELECT statement, and within the FOR XML clause you specify an XML mode: RAW, AUTO, or EXPLICIT.

14. Can a Stored Procedure call itself (recursive). If so then up to what level and can it be control?
Stored procedures are nested when one stored procedure calls another. You can nest stored procedures up to 32 levels. The nesting level increases by one when the called stored procedure begins execution and decreases by one when the called stored procedure completes execution. Attempting to exceed the maximum of 32 levels of nesting causes the whole calling stored procedure chain to fail. The current nesting level for the stored procedures in execution is stored in the @@NESTLEVEL function.
eg:
SET NOCOUNT ON
USE master
IF OBJECT_ID('dbo.sp_calcfactorial') IS NOT NULL
DROP PROC dbo.sp_calcfactorial
GO
CREATE PROC dbo.sp_calcfactorial
@base_number int, @factorial int OUT
AS
DECLARE @previous_number int
IF (@base_number<2) SET @factorial=1 -- Factorial of 0 or 1=1
ELSE BEGIN
SET @previous_number=@base_number-1
EXEC dbo.sp_calcfactorial @previous_number, @factorial OUT -- Recursive call
IF (@factorial=-1) RETURN(-1) -- Got an error, return
SET @factorial=@factorial*@base_number
END
RETURN(0)
GO

calling proc.
DECLARE @factorial int
EXEC dbo.sp_calcfactorial 4, @factorial OUT
SELECT @factorial

15. What is Nested Triggers?
Triggers are nested when a trigger performs an action that initiates another trigger, which can initiate another trigger, and so on. Triggers can be nested up to 32 levels, and you can control whether triggers can be nested through the nested triggers server configuration option.

16. What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?
An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures using the EXEC statement.

17. Difference between view and stored procedure?
Views can have only select statements (create, update, truncate, delete statements are not allowed) Views cannot have “select into”, “Group by” “Having”, ”Order by”

18. What is a Function & what are the different user defined functions?
Function is a saved Transact-SQL routine that returns a value. User-defined functions cannot be used to perform a set of actions that modify the global database state. User-defined functions, like system functions, can be invoked from a query. They also can be executed through an EXECUTE statement like stored procedures.
    i)Scalar Functions
Functions are scalar-valued if the RETURNS clause specified one of the scalar data types
    ii)Inline Table-valued Functions
If the RETURNS clause specifies TABLE with no accompanying column list, the function is an inline function.
    iii)Multi-statement Table-valued Functions
If the RETURNS clause specifies a TABLE type with columns and their data types, the function is a multi-statement table-valued function.

19. What are the difference between a function and a stored procedure?
•    Functions can be used in a select statement where as procedures cannot
•    Procedure takes both input and output parameters but Functions takes only input parameters
•    Functions cannot return values of type text, ntext, image & timestamps where as procedures can
•    Functions can be used as user defined datatypes in create table but procedures cannot
Eg:- create table <tablename>(name varchar(10),salary getsal(name))
Here getsal is a user defined function which returns a salary type, when table is created no storage is allotted for salary type, and getsal function is also not executed, But when we are fetching some values from this table, getsal function get’s executed and the return
Type is returned as the result set.