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

Tuesday, October 6, 2015

Table valued parameters (TVP)

Table values parameters

How we can pass multiple rows in stored procedure or function as a parameter?

Table-valued parameters are a new parameter type in SQL Server 2008. Table-valued parameters are declared by using user-defined table types. You can use table-valued parameters to send multiple rows of data to a Transact-SQL statement or a routine, such as a stored procedure or function, without creating a temporary table or many parameters. This is very helpful when you have requirement to pass dataset to stored procedure or function to manipulate internally. Table-valued parameters are like parameter arrays in OLE DB and ODBC, but offer more flexibility and closer integration with Transact-SQL. Table-valued parameters also have the benefit of being able to participate in set-based operations. In earlier versions of SQL SERVER this is not possible to pass table variable in stored procedure or function. it is not possible to pass a table variable in stored procedure as a parameter, but now in SQL SERVER 2008 or later version we can use Table-Valued Parameter to send multiple rows of data to a stored procedure or a function without creating a temporary table or passing so many parameters.



Table-valued parameters are declared using user-defined table types. To use a Table Valued Parameters we need follow steps shown below:
  • Create a table type and define the table structure
  • Declare a stored procedure that has a parameter of table type.
  • Declare a table type variable and reference the table type.
  • Using the INSERT statement and occupy the variable.
  • After the table variable is created and filled, you can pass the variable to a routine.
  • After the routine is out of scope, the table-valued parameter is no longer available. The type definition remains until it is dropped.

Let us work with an example:-

Create Employee Table and pass the table variable to insert data using procedure. In our example we will create Employee table and then we will query it and see that all the content of table value parameter is inserted into it.

Create Table Employee
(
       EmpID int Primary key,
       FirstName varchar(100),
       MiddleName varchar(100),
       LastName varchar(100),
       EmailId varchar(100)
);
GO
Create a TABLE TYPE and define the table structure:

CREATE TYPE EmployeeType AS TABLE
(
EmpID int,FirstName varchar(100),MiddleName varchar(100),LastName varchar(100),EmailId varchar(100)
);

GO



Declare a STORED PROCEDURE that has a parameter of table type:

CREATE PROCEDURE InsertEmployee

@InsertEmp_TVP EmployeeType READONLY
AS
INSERT INTO Employee(EmpID ,FirstName,MiddleName,LastName,EmailId)
SELECT * FROM @InsertEmp_TVP;
GO

Points to be remember before using table type:-
  • Table-valued parameters must be passed as READONLY parameters to SQL routine. You cannot perform DML operations like UPDATE, DELETE, or INSERT on a table-valued parameter in the body of a routine.
  • You cannot use a table-valued parameter as target of a SELECT INTO or INSERT EXEC statement. A table-valued parameter can be in the FROM clause of SELECT INTO or in the INSERT EXEC string or stored-procedure.


Declare a table type variable and reference the table type.

DECLARE @Employee_TVP AS EmployeeType;

INSERT INTO @Employee_TVP(EmpID ,FirstName,MiddleName,LastName,EmailId)
VALUES
       (1,'Arun',null,'Kumar','arun@tsqlcirclelive.com'),
       (2,'Laxmi','Kant','Azad','laxmi@tsqlcirclelive.com'),
       (3,'Rakesh','Kumar','sharma','rkshrma@tsqlcirclelive.com'),
       (4,'abhi',null,'parihar','abhipar@tsqlcirclelive.com'),
       (5,'Ronald',null,'Disuja','laxmi@tsqlcirclelive.com')

EXEC InsertEmployee @Employee_TVP;


Let’s see if the Data are inserted in the Employee Table

 

Benefits

Table-valued parameters offer more flexibility and in some cases better performance than temporary tables or other ways to pass a list of parameters. Table-valued parameters offer the following benefits:
·         Do not acquire locks for the initial population of data from a client.
·         Provide a simple programming model.
·         Enable you to include complex business logic in a single routine.
·         Reduce round trips to the server.
·         Can have a table structure of different cardinality.
·         Are strongly typed.
·         Enable the client to specify sort order and unique keys.


Restrictions

Table-valued parameters have the following restrictions:
·         SQL Server does not maintain statistics on columns of table-valued parameters.
·         Table-valued parameters must be passed as input READONLY parameters to Transact-SQL routines. You cannot perform DML operations such as UPDATE, DELETE, or INSERT on a table-valued parameter in the body of a routine.
·         You cannot use a table-valued parameter as target of a SELECT INTO or INSERT EXEC statement. A table-valued parameter can be in the FROM clause of SELECT INTO or in the INSERT EXEC string or stored-procedure.


Scope

A table-valued parameter is scoped to the stored procedure, function or dynamic Transact-SQL text, exactly like other parameters. Similarly, a variable of table type has scope like any other local variable that is created by using a DECLARE statement. You can declare table-valued variables within dynamic Transact-SQL statements and pass these variables as table-valued parameters to stored procedures and functions.

Security

Permissions for table-valued parameters follow the object security model for SQL Server, by using the Transact-SQL keywords: CREATE, GRANT, DENY, ALTER, CONTROL, TAKE OWNERSHIP, REFERENCES, EXECUTE, VIEW DEFINITION, and REVOKE.

Conclusion


Table-Valued Parameters is a new parameter type in SQL SERVER 2008 that provides efficient way of passing the table type variable than using the temporary table or passing so many parameters. It helps in using complex business logic in single routine. They reduce Round Trips to the server making the performance better.