Monday, December 28, 2015

What is an execution plan? When would you use it? How would you view the execution plan?

An execution plan is basically a road map that graphically or textually shows the data retrieval methods chosen by the SQL server’s query optimizer for a stored procedure or ad hoc query. Execution plans are very useful for helping a developer understand and analyze the performance characteristics of a query or stored procedure, since the plan is used to execute the query or stored procedure.

In many SQL systems, a textual execution plan can be obtained using a keyword such as EXPLAIN, and visual representations can often be obtained as well. In Microsoft SQL Server, the Query Analyzer has an option called “Show Execution Plan” (located on the Query drop down menu). If this option is turned on, it will display query execution plans in a separate window when a query is run.

Friday, November 13, 2015

How do we insert the results of the stored procedure in a table?



This question has two crinkle answers –
·         When the table is already created.

·         When the table is to be created run time.

Let us create a stored procedure which we will use for our example.

We can execute this stored procedure using the following script.
EXEC GetAllTables
Now let us see two different situations where we will insert the data of the stored procedure straight into the table.
1) Schema Known – Table Created Previously
If we know the schema of the stored procedure result set we can build a table previously and execute following code.

CREATE TABLE #TestTable ([TableName] VARCHAR(256), [TABLE_TYPE] CHAR(2));
INSERT INTO #TestTable
EXEC GetAllTables
-- Select Table
SELECT *
FROM #TestTable;
The drawback of this code is that if due to any reason the stored procedure returns more or less columns it will throw an error.
2) Unknown Schema – Table Created at Runtime
There are cases when we do know the result set of the stored procedure and we want to colonize the table based of it. We can execute following code.

SELECT * INTO #TestTableT FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;',
'EXEC tempdb.dbo.GetAllTables')
-- Select Table
SELECT *
FROM #TestTableT;

The drawback of this code is that it bit complex but it generally works fine in the case of the column names are not known.
Just footnote that if you are getting error in this method enable ad hoc distributed queries by executing following query in SSMS.
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO

Hope this will give you some idea export stored procedure results to table.

Please share your thought on both the case.



Thursday, October 8, 2015

How we can convert Comma Separated Value to Rows and Vice Versa?


How we can convert Comma Separated Value to Rows and Vice Versa?

Basic fundamental


While we are working on reporting some circumstances comes when we have to deal with comma separated values or any other characters in single column but we need those values in rows or separated with multiple columns. Also some time we need to convert rows into comma separated values. Now we will discuss on conversion of comma separated values to rows then we will discuss how we can create comma separated values from rows.

Sample: - “abcd, def, ghi, jkl, mno, xyz” these point to one column values.

Converting Comma Separated Value to Rows

We will use stuff function, charindex, ltrim, rtrim,substring

Steps we follow
  • 1.     We will create function, which take column values as parameter.
  • 2.     Iterate internally till end of the last values separated with special characters.
  • 3.     Insert each values to table variable
  • 4.     Then select inserted values from table as output of stored procedure.

It makes use of CHARINDEX inbuilt function to search for the existence of commas in the input parameter and returns the first position. It does that as long as the position is greater than zero. Then it makes use of the STUFF inbuilt function to replace a part of the main input parameter with a zero length string; effectively removing the value before the comma, which has already been extracted from the main input parameter and inserted into the table. We will use LTRIM and RTRIM functions to remove any extra spaces from the beginning or end of the value if there are any.









Now we will discuss how we can create rows into comma separated values.

For achieving desired output from rows to comma separated values we will use COALESCE FUNCTION. The COALESCE function takes a list of parameters, separated by commas, evaluates them and returns the value of the first of its input parameters that is not NULL.
Though COALESCE and ISNULL functions have a similar purpose, they can behave differently. For example, ISNULL function is evaluated only once whereas the input values for the COALESCE function can be evaluated multiple times or until it reaches to the first not-NULL value to return.
In example, I have considered the comma as a character to separate values.



you can created function which will concatenate rows separated with user defined special character.

Wednesday, October 7, 2015

HOW WE CAN GET WHO IS CONNECTED TO DATABASE?


Some time we need to know that who is using database as of now or who all are connected to specific database.

We can use sysprocesses to know the all the detail for specific database.
sysprocesses contains information about processes that are running on an instance of SQL Server. These processes can be client processes or system processes. To access sysprocesses, you must be in the master database context, or you must use the master.dbo.sysprocesses three-part name.

If a user has VIEW SERVER STATE permission on the server, the user will see all executing sessions in the instance of SQL Server; otherwise, the user will see only the current session.

Column name
Data type
Description
spid
smallint
SQL Server session ID.
kpid
smallint
Windows thread ID.
blocked
smallint
ID of the session that is blocking the request. If this column is NULL, the request is not blocked, or the session information of the blocking session is not available (or cannot be identified).
-2 = The blocking resource is owned by an orphaned distributed transaction.
-3 = The blocking resource is owned by a deferred recovery transaction.
-4 = Session ID of the blocking latch owner could not be determined due to internal latch state transitions.
waittype
binary(2)
Reserved.
waittime
bigint
Current wait time in milliseconds.
0 = Process is not waiting.
lastwaittype
nchar(32)
A string indicating the name of the last or current wait type.
waitresource
nchar(256)
Textual representation of a lock resource.
dbid
smallint
ID of the database currently being used by the process.
uid
smallint
ID of the user that executed the command. Overflows or returns NULL if the number of users and roles exceeds 32,767. For more information, see Querying the SQL Server System Catalog.
cpu
int
Cumulative CPU time for the process. The entry is updated for all processes, regardless of whether the SET STATISTICS TIME option is ON or OFF.
physical_io
bigint
Cumulative disk reads and writes for the process.
memusage
int
Number of pages in the procedure cache that are currently allocated to this process. A negative number indicates that the process is freeing memory allocated by another process.
login_time
datetime
Time at which a client process logged into the server. For system processes, the time at which the SQL Server startup occurred is stored.
last_batch
datetime
Last time a client process executed a remote stored procedure call or an EXECUTE statement. For system processes, the time at which the SQL Server startup occurred is stored.
ecid
smallint
Execution context ID used to uniquely identify the subthreads operating on behalf of a single process.
open_tran
smallint
Number of open transactions for the process.
status
nchar(30)
Process ID status. The possible values are:
dormant = SQL Server is resetting the session.
running = The session is running one or more batches. When Multiple Active Result Sets (MARS) is enabled, a session can run multiple batches. For more information, see Using Multiple Active Result Sets (MARS).
background = The session is running a background task, such as deadlock detection.
rollback = The session has a transaction rollback in process.
pending = The session is waiting for a worker thread to become available.
runnable = The task in the session is in the runnable queue of a scheduler while waiting to get a time quantum.
spinloop = The task in the session is waiting for a spinlock to become free.
suspended = The session is waiting for an event, such as I/O, to complete.
sid
binary(86)
Globally unique identifier (GUID) for the user.
hostname
nchar(128)
Name of the workstation.
program_name
nchar(128)
Name of the application program.
hostprocess
nchar(10)
Workstation process ID number.
cmd
nchar(16)
Command currently being executed.
nt_domain
nchar(128)
Windows domain for the client, if using Windows Authentication, or a trusted connection.
nt_username
nchar(128)
Windows user name for the process, if using Windows Authentication, or a trusted connection.
net_address
nchar(12)
Assigned unique identifier for the network adapter on the workstation of each user. When a user logs in, this identifier is inserted in the net_address column.
net_library
nchar(12)
Column in which the client's network library is stored. Every client process comes in on a network connection. Network connections have a network library associated with them that enables them to make the connection. For more information, seeNetwork Protocols and TDS Endpoints.
loginame
nchar(128)
Login name.
context_info
binary(128)
Data stored in a batch by using the SET CONTEXT_INFO statement.
sql_handle
binary(20)
Represents the currently executing batch or object.
Note   This value is derived from the batch or memory address of the object. This value is not calculated by using the SQL Server hash-based algorithm.
stmt_start
int
Starting offset of the current SQL statement for the specified sql_handle.
stmt_end
int
Ending offset of the current SQL statement for the specified sql_handle.
-1 = Current statement runs to the end of the results returned by the fn_get_sql function for the specified sql_handle.
request_id
int
ID of request. Used to identify requests running in a specific session.

SQL Query:-

select spid, status, loginame,
hostname, blocked, db_name(dbid) as databasename, cmd
from master..sysprocesses
where db_name(dbid) like '%TSQL%'

and spid > 50