Search This Blog
2010-05-31
Different Isolation Level in SQL Server 2005
READ UNCOMMITTED
READ COMMITTED
REPEATABLE READ
SERIALIZABLE
Read uncommitted:When it's used, SQL Server not issue shared locks while reading data. So, you can read an uncommitted transaction that might get rolled back later. This isolation level is also called dirty read. This is the lowest isolation level. It ensures only that a physically corrupt data will not be read.
Read committed:This is the default isolation level in SQL Server. When it's used, SQL Server will use shared locks while reading data. It ensures that a physically corrupt data will not be read and will never read data that another application has changed and not yet committed, but it does not ensure that the data will not be changed before the end of the transaction.
Repeatable read:When it's used, the dirty reads and nonrepeatable reads cannot occur. It means that locks will be placed on all data that is used in a query, and another transactions cannot update the data.
Serializable:Most restrictive isolation level. When it's used, then phantom values cannot occur. It prevents other users from updating or inserting rows into the data set until the transaction is complete.
SET TRANSACTION ISOLATION LEVEL
{
READ COMMITTED
| READ UNCOMMITTED
| REPEATABLE READ
| SERIALIZABLE
}
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
GO
DBCC USEROPTIONS
GO
Different Concurrency Level:
Nonrepeatable read
When a transaction reads the same row more than one time, and between the
two (or more) reads, a separate transaction modifies that row. Because the
row was modified between reads within the same transaction, each read
produces different values, which introduces inconsistency.Nonrepeatable read—Nonrepeatable reads happen when a transaction performs the same query two or more times and each time the data is different. This is usually due to another concurrent transaction updating the data
between the queries.
Dirty read—Dirty reads occur when one transaction reads data that has been written but not yet committed by another transaction. If the changes are later rolled back, the data obtained by the first transaction will be invalid.
phantom
Phantom behavior occurs when a transaction attempts to select a row that
does not exist and a second transaction inserts the row before the first
transaction finishes. If the row is inserted, the row appears as a phantom
to the first transaction, inconsistently appearing and disappearing.
2010-05-02
How to get records in random order from a sql query in sql server?
SELECT Subject FROM dbo.test ORDER BY NEWID()
What are the default databases of SQL Server
1.Master (Controls other Databases):The Master database holds information for all databases located on the SQL Server instance and is the glue that holds the engine together. Because SQL Server cannot start without a functioning master database, you must administer this database with care.
2.Model (Template for new Databases)
3.Msdb (Scheduling and Job Information):The msdb database stores information regarding database backups, SQL Agent information, DTS packages, SQL Server jobs, and some replication information such as for log shipping.
4.Tempdb (Temporary Storage):The tempdb holds temporary objects such as global and local temporary tables and stored procedures. The model is essentially a template database used in the creation of any new user database created in the instance.
2010-04-24
Maximum Capacity of different properties for SQL Server
SQL Server Database Engine object | Maximum sizes/numbers SQL Server (32-bit) | Maximum sizes/numbers SQL Server (64-bit) |
---|---|---|
Batch size 1 | 65,536 * Network Packet Size | 65,536 * Network Packet Size |
Bytes per short string column | 8,000 | 8,000 |
Bytes per GROUP BY, ORDER BY | 8,060 | 8,060 |
Bytes per index key2 | 900 | 900 |
Bytes per foreign key | 900 | 900 |
Bytes per primary key | 900 | 900 |
Bytes per row8 | 8,060 | 8,060 |
Bytes in source text of a stored procedure | Lesser of batch size or 250 MB | Lesser of batch size or 250 MB |
Bytes per varchar(max), varbinary(max), xml, text, or image column | 2^31-1 | 2^31-1 |
Characters per ntext or nvarchar(max) column | 2^30-1 | 2^30-1 |
Clustered indexes per table | 1 | 1 |
Columns in GROUP BY, ORDER BY | Limited only by number of bytes | Limited only by number of bytes |
Columns or expressions in a GROUP BY WITH CUBE or WITH ROLLUP statement | 10 | 10 |
Columns per index key7 | 16 | 16 |
Columns per foreign key | 16 | 16 |
Columns per primary key | 16 | 16 |
Columns per nonwide table | 1,024 | 1,024 |
Columns per wide table | 30,000 | 30,000 |
Columns per SELECT statement | 4,096 | 4,096 |
Columns per INSERT statement | 4096 | 4096 |
Connections per client | Maximum value of configured connections | Maximum value of configured connections |
Database size | 524,272 terabytes | 524,272 terabytes |
Databases per instance of SQL Server | 32,767 | 32,767 |
Filegroups per database | 32,767 | 32,767 |
Files per database | 32,767 | 32,767 |
File size (data) | 16 terabytes | 16 terabytes |
File size (log) | 2 terabytes | 2 terabytes |
Foreign key table references per table4 | 253 | 253 |
Identifier length (in characters) | 128 | 128 |
Instances per computer | 50 instances on a stand-alone server for all SQL Server editions except for Workgroup. Workgroup supports a maximum of 16 instances per computer.SQL Server supports 25 instances on a failover cluster. | 50 instances on a stand-alone server.25 instances on a failover cluster. |
Length of a string containing SQL statements (batch size)1 | 65,536 * Network packet size | 65,536 * Network packet size |
Locks per connection | Maximum locks per server | Maximum locks per server |
Locks per instance of SQL Server5 | Up to 2,147,483,647 | Limited only by memory |
Nested stored procedure levels6 | 32 | 32 |
Nested subqueries | 32 | 32 |
Nested trigger levels | 32 | 32 |
Nonclustered indexes per table | 999 | 999 |
Number of distinct expressions in the GROUP BY clause when any of the following are present: CUBE, ROLLUP, GROUPING SETS, WITH CUBE, WITH ROLLUP | 32 | 32 |
Number of grouping sets generated by operators in the GROUP BY clause | 4,096 | 4,096 |
Parameters per stored procedure | 2,100 | 2,100 |
Parameters per user-defined function | 2,100 | 2,100 |
REFERENCES per table | 253 | 253 |
Rows per table | Limited by available storage | Limited by available storage |
Tables per database3 | Limited by number of objects in a database | Limited by number of objects in a database |
Partitions per partitioned table or index | 1,000 | 1,000 |
Statistics on non-indexed columns | 30,000 | 30,000 |
Tables per SELECT statement | Limited only by available resources | Limited only by available resources |
Triggers per table3 | Limited by number of objects in a database | Limited by number of objects in a database |
Columns per UPDATE statement (Wide Tables) | 4096 | 4096 |
User connections | 32,767 | 32,767 |
XML indexes | 249 | 249 |
1Network Packet Size is the size of the tabular data stream (TDS) packets used to communicate between applications and the relational Database Engine. The default packet size is 4 KB, and is controlled by the network packet size configuration option.2The maximum number of bytes in any index key cannot exceed 900 in SQL Server. You can define a key using variable-length columns whose maximum sizes add up to more than 900, provided no row is ever inserted with more than 900 bytes of data in those columns. In SQL Server, you can include nonkey columns in a nonclustered index to avoid the maximum index key size of 900 bytes.3Database objects include objects such as tables, views, stored procedures, user-defined functions, triggers, rules, defaults, and constraints. The sum of the number of all objects in a database cannot exceed 2,147,483,647.4Although a table can contain an unlimited number of FOREIGN KEY constraints, the recommended maximum is 253. Depending on the hardware configuration hosting SQL Server, specifying additional FOREIGN KEY constraints may be expensive for the query optimizer to process.5This value is for static lock allocation. Dynamic locks are limited only by memory.6If a stored procedure accesses more than 8 databases, or more than 2 databases in interleaving, you will receive an error.7If the table contains one or more XML indexes, the clustering key of the user table is limited to 15 columns because the XML column is added to the clustering key of the primary XML index. In SQL Server, you can include nonkey columns in a nonclustered index to avoid the limitation of a maximum of 16 key columns. For more information, see Index with Included Columns.8 SQL Server supports row-overflow storage which enables variable length columns to be pushed off-row. Only a 24-byte root is stored in the main record for variable length columns pushed out of row; because of this, the effective row limit is higher than in previous releases of SQL Server. For more information, see the "Row-Overflow Data Exceeding 8 KB" topic in SQL Server Books Online.
Document Obtain From:
http://msdn.microsoft.com/en-us/library/ms143432.aspx
Summarizing Data Using ROLLUP and CUBE
For example, a simple table Inventory contains the following:
Item Color Quantity
-------------------- -------------------- --------------------------
Table Blue 124
Table Red 223
Chair Blue 101
Chair Red 210
This query generates a subtotal report:
SELECT CASE WHEN (GROUPING(Item) = 1) THEN 'ALL'
ELSE ISNULL(Item, 'UNKNOWN')
END AS Item,
CASE WHEN (GROUPING(Color) = 1) THEN 'ALL'
ELSE ISNULL(Color, 'UNKNOWN')
END AS Color,
SUM(Quantity) AS QtySum
FROM Inventory
GROUP BY Item, Color WITH ROLLUP
Item Color QtySum
-------------------- -------------------- --------------------------
Chair Blue 101.00
Chair Red 210.00
Chair ALL 311.00
Table Blue 124.00
Table Red 223.00
Table ALL 347.00
ALL ALL 658.00
(7 row(s) affected)
If the ROLLUP keyword in the query is changed to CUBE, the CUBE result set is the same, except these two additional rows are returned at the end:
ALL Blue 225.00
ALL Red 433.00
Following are the specific differences between CUBE and ROLLUP:
CUBE generates a result set that shows aggregates for all combinations of values in the selected columns.
ROLLUP generates a result set that shows aggregates for a hierarchy of values in the selected columns.
2010-04-13
Rank Function in SQL Server
name | territory | sales_amount |
A | X | 100 |
B | X | 200 |
C | X | 200 |
D | X | 300 |
E | X | 400 |
F | Y | 300 |
G | Y | 300 |
H | Y | 500 |
I | Y | 600 |
J | Z | 200 |
K | Z | 700 |
NTILE (integer_expression) OVER ( [ <partition_by_clause> ] <order_by_clause> )
SELECT
name
,territory
,ROW_NUMBER() OVER ( ORDER BY sales_amount ) AS [row_number]
,RANK() OVER ( ORDER BY sales_amount ) AS [rank]
,DENSE_RANK() OVER ( ORDER BY sales_amount ) AS [dense_rank]
,NTILE(4) OVER ( ORDER BY sales_amount ) AS [ntile]
FROM
sales_employee
name | territory | sales_amount | ROW_NUMBER | RANK | DENSE_RANK | NTILE |
A | X | 100 | 1 | 1 | 1 | 1 |
B | X | 200 | 2 | 2 | 2 | 1 |
C | X | 200 | 3 | 2 | 2 | 1 |
D | X | 300 | 5 | 5 | 3 | 2 |
E | X | 400 | 8 | 8 | 4 | 3 |
F | Y | 300 | 6 | 5 | 3 | 2 |
G | Y | 300 | 7 | 5 | 3 | 3 |
H | Y | 500 | 9 | 9 | 5 | 3 |
I | Y | 600 | 10 | 10 | 6 | 4 |
J | Z | 200 | 4 | 2 | 2 | 2 |
K | Z | 700 | 11 | 11 | 7 | 4 |
SELECT
name
,territory
,ROW_NUMBER() OVER ( PARTITION BY territory ORDER BY sales_amount ) AS [row_number]
,RANK() OVER ( PARTITION BY territory ORDER BY sales_amount ) AS [rank]
,DENSE_RANK() OVER ( PARTITION BY territory ORDER BY sales_amount ) AS [dense_rank]
,NTILE(4) OVER ( PARTITION BY territory ORDER BY sales_amount ) AS [ntile]
FROM
sales_employee
name | territory | sales_amount | ROW_NUMBER | RANK | DENSE_RANK | NTILE |
A | X | 100 | 1 | 1 | 1 | 1 |
B | X | 200 | 2 | 2 | 2 | 1 |
C | X | 200 | 3 | 2 | 2 | 2 |
D | X | 300 | 4 | 4 | 3 | 3 |
E | X | 400 | 5 | 5 | 4 | 4 |
F | Y | 300 | 1 | 1 | 1 | 1 |
G | Y | 300 | 2 | 1 | 1 | 2 |
H | Y | 500 | 3 | 3 | 2 | 3 |
I | Y | 600 | 4 | 4 | 3 | 4 |
J | Z | 200 | 1 | 1 | 1 | 1 |
K | Z | 700 | 2 | 2 | 2 | 2 |
2010-03-18
Get all Child IDs from Self Referential Table(DFS)
and you need a stored proc which will take the parent key and return all the Childs and Sub Childs ID's along with the parent key.Like
if you supply :2
it will return 2,4,5,6,7,8 and
if you supply :5
it will return :5,7,8
In this context, you can create the following SP
Stored Proc:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[FnGetChildIDs]
@KEYID INT,
@IDCOL VARCHAR(20),
@IDVAL VARCHAR(20),
@PIDCOL VARCHAR(20),
@TABLENAME VARCHAR(200)
AS
DECLARE @STR VARCHAR(2000)
Begin
SET @STR= 'WITH RECURSIONCTE(' + @IDCOL +',CATEGORYDESCRIPTION)
AS
(
SELECT '+@IDCOL +','+@IDVAL +'
FROM ' + @TABLENAME +'
WHERE ' +@IDCOL +'='+ CAST(@KEYID AS VARCHAR) +
' UNION ALL
SELECT R1.' +@IDCOL+',
R1.'+@IDVAL +
' FROM '+@TABLENAME + ' AS R1
JOIN RECURSIONCTE AS R2 ON R1.'+@PIDCOL +'=R2.'+@IDCOL+'
)
SELECT '+ @IDCOL +' FROM RECURSIONCTE'
PRINT(@STR)
EXEC (@STR)
End
if @@Error <> 0
Begin
Raiserror ('GetChildIDs',16,1)
End
Table Schema
CREATE TABLE [dbo].[tblProductMaster](
[ProductID] [bigint] NOT NULL,
[Name] [varchar](50) NULL,
[ParentID] [bigint] NULL,
CONSTRAINT [PK_tblProductMaster] PRIMARY KEY CLUSTERED
(
[ProductID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Execute the SP:
EXEC FNGETCHILDIDS 2,'PRODUCTID','NAME','PARENTID','DBO.TBLPRODUCTMASTER'
2010-02-24
Dynamic Bulk Copy using OPENXML
USE [WMMM]
GO
/****** Object: StoredProcedure [dbo].[spBulkInsert] Script Date: 02/24/2010 10:21:49 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spBulkInsert]
@ITEMS NTEXT,
@TABLENAME VARCHAR(2000),
@COLUMN_NAME VARCHAR(2000),
@COLUMNNAMESWITHDATATYPE VARCHAR(2000),
@DELETEOLDRECORD VARCHAR(1)
AS
DECLARE @INSERT AS NVARCHAR(2000)
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION;
if @DELETEOLDRECORD='Y'
BEGIN
EXEC('DELETE FROM '+@TABLENAME)
END
DECLARE @HDOC INT
EXEC SP_XML_PREPAREDOCUMENT @HDOC OUTPUT,@ITEMS
SET @INSERT=
'INSERT INTO '+@TABLENAME +'('+@COLUMN_NAME +')
SELECT '+ @COLUMN_NAME +'
FROM OPENXML (@HDOC2, ''/ITEMS/ITEM'',2)
WITH ('+ @COLUMNNAMESWITHDATATYPE +') XMLITEMS'
DECLARE @PARMDEFINITION NVARCHAR(500);
SET @PARMDEFINITION = N'@HDOC2 INT';
EXECUTE SP_EXECUTESQL @INSERT, @PARMDEFINITION,
@HDOC2 = @HDOC;
EXEC SP_XML_REMOVEDOCUMENT @HDOC
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
EXEC dbo.sp_GetErrorInfo
END CATCH
END
Execute The Above Sp Input Parameters :
USE [WMMM]
GO
DECLARE @return_value int
EXEC @return_value = [dbo].[spBulkInsert]
@ITEMS = N'<ITEMS><ITEM><PRODUCTID>1</PRODUCTID><NAME>..</NAME><PARENTID>0</PARENTID></ITEM><ITEM><PRODUCTID>2</PRODUCTID><NAME>CHOCO DELIGHT</NAME><PARENTID>1</PARENTID></ITEM><ITEM><PRODUCTID>3</PRODUCTID><NAME>WOW VANILLA</NAME><PARENTID>1</PARENTID></ITEM><ITEM><PRODUCTID>4</PRODUCTID><NAME>CHOCO2</NAME><PARENTID>2</PARENTID></ITEM><ITEM><PRODUCTID>5</PRODUCTID><NAME>CHOCO2_3</NAME><PARENTID>4</PARENTID></ITEM><ITEM><PRODUCTID>6</PRODUCTID><NAME>CHOCO2_3_4</NAME><PARENTID>5</PARENTID></ITEM><ITEM><PRODUCTID>7</PRODUCTID><NAME>CHOCO2_3_4_5</NAME><PARENTID>6</PARENTID></ITEM></ITEMS>',
@TABLENAME = N'TBLTEST',
@COLUMN_NAME = N'PRODUCTID,NAME,PARENTID',
@COLUMNNAMESWITHDATATYPE = N'PRODUCTID BIGINT,NAME VARCHAR(50),PARENTID BIGINT',
@DELETEOLDRECORD = N'N'
SELECT 'Return Value' = @return_value
GO
--@COLUMN_NAME and @COLUMNNAMESWITHDATATYPE must be match with the destination
--table name i.e TBLTEST
Table Schema of tblTest:
USE [WMMM]
GO
/****** Object: Table [dbo].[tblTest] Script Date: 02/24/2010 10:29:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tblTest](
[ProductID] [bigint] NULL,
[Name] [varchar](50) NULL,
[ParentID] [bigint] NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF