Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

Friday, January 1, 2010

Working with Hierarchical data in SQL Server 2008

In my series on SQL Server 2008, one of the features I had missed was the HierarchyId datatype and its usage. I came across this recently and decided to take a peek into what it does. This post covers my thoughts on the HierarchyId datatype.

At the time of this writing, I am still not convinced on the value add the HierarchyId datatype provides over traditional parent/child storage mechanisms. More on that later. For now, we will deal with how the datatype works and how it can be used to store hierarchial data.

The big advantage with HierarchyId is that it is optimised to store data in a tree structure thereby making it simpler for developers to query and update hierarchical information.  The important thing to keep in mind is that using the hierarchyid by itself does not mean that data is stored in a tree structure. It is the responsibility of the application to make sure that the data is stored in the desired structure. HierarchyId just acts as an enabler.

To demonstrate this, I will work through an example where we have to store the list of folders and files in the database. I have created a table with the following structure.

Create Table FileExplorer
(
    ItemId HierarchyId Primary Key,
    ItemLevel as ItemId.GetLevel(),
    ItemName varchar(100)   
)

I will touch upon the ItemLevel column later. Do note that the HierarchyId datatype by itself is not unique. It is application’s responsibility again to maintain the uniqueness of the ItemId column and hence I have declared a PrimaryKey on that column.

Coming to ItemLevel column, the primary purpose of that is to enable breadth first ordering. Typically, hierarchy ids can be breadth first or depth first indexed. You can find the details and working of both these types of ordering here.

Now, let us create the breadth first index. Depending on how many levels (called fan-outs) you plan to store, your indexing strategy will vary. It is not necessary to create both the indexes for all the scenarios.

CREATE INDEX FileExplorer_Breadth_First
ON FileExplorer(ItemLevel,ItemId)
GO

Since the FileExplorer table already has a Primary key, the above index will be created as a non-clustered index.

Now that we have created the table, let us start loading data into the table. If you haven’t already noted, let me point out that the ItemId is not declared as an Identity (it cannot be, actually) and hence it is the application’s responsibility again to make sure that the generated ids are unique. In addition, to ensure the tree structure, we have to make sure the id generated is based on the parent id.

The stored procedure to insert a new file or folder is

CREATE PROCEDURE InsertFile(@folderId hierarchyid, @ItemName nvarchar(100) )
AS
BEGIN
    DECLARE @last_child hierarchyid

SELECT @last_child = MAX(ItemId) FROM FileExplorer
    WHERE ItemId.GetAncestor(1) = @folderId
INSERT FileExplorer (ItemId, ItemName)
SELECT @folderId.GetDescendant(@last_child, NULL), @ItemName
END ;

 

Let us examine this procedure for a second.  The ItemId.GetAncestor(1) gets the immediate parent of the ItemId. So essentially, the select statement gets  the last valid file under the given folder id. Now that we have the last inserted item under the parent, our new file has to be created as a peer to that item.

This is done by the second select statement in the procedure. We use the GetDescendant method to create a child similar to another child, in this case, the item retrieved from the previous select. It wouldn’t be out of place to mention here that this is where our breadth first ordering helps.

The tree can also be maintained by creating a parentId column that references the itemId but there is also a performance drag associated with that approach. A snapshot of the data after inserting some rows is as below

Results

Note how the item level computes itself. The folders testFolderChild and TestfolderChildPeer are at the same level and have the same parent –TestFolder.

Let us now see how we can retrieve the list of parents for a given node. To do this, I had to write a stored procedure using CTEs. Below is the stored procedure I wrote

create proc dbo.GetAncestors(@ItemId hierarchyId)
as
begin

With AncestorsList(Itemid, ItemName, ItemLevel, Parent)
As
(
    Select ItemId, ItemName, ItemLevel, ItemId.GetAncestor(1) as Parent from Fileexplorer where ItemId=@ItemId
    UNION ALL
    Select fe.ItemId, fe.ItemName, fe.ItemLevel, fe.Itemid.GetAncestor(1) from FileExplorer fe Inner Join AncestorsList al
    ON fe.ItemId = al.Parent
)   
    Select fe.ItemId, fe.ItemName, fe.ItemLevel from FileExplorer fe INNER JOIN
    AncestorsList al on fe.ItemId = al.Itemid
end

 

If you are familiar with CTEs then most of the code above is self explanatory. My anchor members gets the first ancestor of the given node. This is then executed recursively by my recursive query. The last select executes the CTE to return the resultset.

Having seen most of the uses of HierarchyId, its biggest drawback lies in the fact that it still needs the developers to do a lot. For fan-outs of less that 2 levels, I still feel the self referencing table is faster than using the hierarchyId. I strongly believe that Microsoft still has some work left to do with the HierarchyId datatype to make sure it is a bit more easier to implement.

That though concludes this post. If you are looking to work with HierarchyIds, I hope this post has given you an idea of where to start. Hope to be back soon with something else. Happy Coding!!!!!!

Sunday, October 4, 2009

Using Table Value Parameters in SQL Server 2008

Table-valued parameter is another exciting new feature in SQL Server 2008. Essentially, TVP solves the problem of inserting multiple rows into the database. Various solutions have been implemented to achieve this, ranging from round trips for every row to comma separated values. With TVP, you can insert multiple rows with a single round trip to the server without having the additional overheads of composition and de-composition of values.

TVP is not entirely new to SQL Server. SQL Server 2000 introduced the table variables which can be used to store a set of records. Where TVP builds on it, is the ability to pass them as input parameters to stored procedures or functions. This could not be done with table variables.

Let us look at some of the features of TVP before we see how they can be used to insert data.

  • TVPs can participate in Set based operations.
  • They are strongly typed
  • You cannot perform DML operations on TVPs. They can be passed as only READ-ONLY parameters to stored procedures\functions
  • Remember that TVPs are materialized in the TempDB. Essentially, it means that if you insert more rows into your TVP, the size of TempDB is what gets affected.

Having seen what TVP is, let us now move onto build an example which will actually use TVP. Here, I will show you a very common scenario that we use for multiple entries. We have an order and each order is comprised of multiple products. I have created the necessary tables using the scripts below

   1: Create table dbo.Products



   2: (



   3: ProductId int IDENTITY(1,1) PRIMARY KEY,



   4: ProductName varchar(250),



   5: ItemRate decimal



   6: )



   7:  



   8: Create table dbo.Orders



   9: (



  10:     OrderId int IDENTITY(1,1) Primary key,



  11:     OrderDate datetime,



  12:     OrderStatus int



  13: )



  14:  



  15: Create Table dbo.OrderDetails



  16: (



  17:     OrderId int Foreign Key references Orders(OrderId),



  18:     ProductId int Foreign Key references Products(ProductId),



  19:     Quantity int,



  20:     Amount decimal



  21: )




I have also inserted data for the tables above. The next thing to do is to create a user defined type that will insert data into the OrderDetails table.





   1: Create type dbo.OrderParam as Table



   2: (ProductId int, Quantity int, Amount decimal)








Now that the type has been created, let me go ahead and create a stored procedure that takes the just created type as an input parameter.





   1: Create proc dbo.InsertOrders



   2: @OrderItems OrderParam ReadOnly



   3: as



   4: begin



   5:     Declare @iOrderId int



   6:     Insert into Orders values (GETDATE(),0)



   7:     Select @iOrderId=SCOPE_IDENTITY()



   8:     Insert into OrderDetails(OrderId, ProductId, Quantity, Amount)



   9:         Select @iOrderId, ProductId, Quantity, Amount from @OrderItems



  10: end




Notice the fact that the TVPs have been declared read only. Also pay attention to the second insert statement. The values are inserted from the input parameter using a single select statement. The only remaining thing to do is to call this stored procedure from the front end.



For this purpose, I have created a data grid where users select the orders and save it into the database. Below is the code that goes into the Save Click routine.





   1: private void SaveButton_Click(object sender, EventArgs e)



   2:         {



   3:             //create a new datatable to hold the grid data



   4:             DataTable OrderParam = new DataTable();



   5:             //the columns are the same as the TVP type



   6:             OrderParam.Columns.Add("ProductId", typeof(int));



   7:             OrderParam.Columns.Add("Quantity", typeof(int));



   8:             OrderParam.Columns.Add("Amount", typeof(decimal));



   9:  



  10:  



  11:             //loop through the grid to load data into the datatable



  12:             foreach (DataGridViewRow item in grdOrders.Rows)



  13:             {



  14:                 DataGridViewComboBoxCell prodCell = (DataGridViewComboBoxCell) item.Cells[0];



  15:                 if (prodCell.Value != null)



  16:                 {



  17:                     DataRow prdRow = OrderParam.NewRow();



  18:                     prdRow[0] = prodCell.Value;



  19:                     prdRow[1] = item.Cells[1].Value;



  20:                     prdRow[2] = item.Cells[2].Value;



  21:                     OrderParam.Rows.Add(prdRow);



  22:                 }



  23:             }



  24:             //connect to the database to insert the values.



  25:             var connString = ConfigurationManager.ConnectionStrings["DatabaseConn"].ConnectionString;



  26:             SqlConnection dbConn = new SqlConnection(connString);



  27:             dbConn.Open();



  28:             using(SqlCommand cmd = new SqlCommand("InsertOrders", dbConn))



  29:             {



  30:               cmd.CommandType = CommandType.StoredProcedure;



  31:               cmd.Parameters.AddWithValue("OrderItems", OrderParam);



  32:               cmd.ExecuteNonQuery();



  33:             }



  34:             dbConn.Close();



  35:         }




The only thing worth noticing is that I have used a datatable which is quite logical because TVPs are tables anyways. As you can see, the savings in the number of round trips to the database is enormous. The USP of the TVPs lie in the fact that they are not hard to implement at all.  Have fun!!!

Saturday, September 12, 2009

CLR Integration Changes in SQL Server 2008

CLR Integration was first introduced in SQL Server 2005. Though there was a lot of excitement when the feature was  introduced, it has since fizzled off. Personally, I think CLR Integration is one of the most underused features of SQL Server. For some reason, we have not been able to move away from extended procedures or UDFs to writing CLR Integrated code.

In SQL Server 2008, there are two noticeable introductions to CLR Introduction. One is the support for LINQ and the other is the support for Nullable types.

To enable CLR support in SQL Server, you first have to switch it on. This is done by running the sp_configure with clr enabled = 1.  One thing to keep in mind is when you are using nullable types, you cannot use the automatic deployment option within Visual Studio 2008. You will have to register your assemblies manually. I will briefly show you how it is done.

Once you have turned the support for CLR on, the next step is to create your assembly. For this, I have a stored procedure written in Visual Studio. The code for the same is as below

 

   1: using System;



   2: using System.Data;



   3: using System.Data.SqlClient;



   4: using System.Data.SqlTypes;



   5: using Microsoft.SqlServer.Server;



   6:  



   7:  



   8: public partial class StoredProcedures



   9: {



  10:     [Microsoft.SqlServer.Server.SqlProcedure]



  11:     public static void SearchEmployee(Int64? iEmployeeId, out Int32? iVacationhours)



  12:     {



  13:         iVacationhours = null;



  14:         if (iEmployeeId !=null)



  15:         {



  16:             //open the sql connection with the current context



  17:             using (SqlConnection connection = new SqlConnection("context connection=true"))



  18:             {



  19:                 //open the connection



  20:                 connection.Open();



  21:                 //build the query and execute it               



  22:                 string query = "Select VacationHours from HumanResources.Employee where EmployeeId = " + iEmployeeId.ToString();



  23:                 SqlCommand sCommand = new SqlCommand(query, connection);



  24:                 SqlDataReader vacationReader = sCommand.ExecuteReader();



  25:                 using (vacationReader)



  26:                 {



  27:                     vacationReader.Read();



  28:                     iVacationhours = vacationReader.GetInt32(0);



  29:                 }



  30:             }            



  31:         }



  32:         



  33:  



  34:     }



  35: };






The code just returns the vacation hours for a given employee. The point worth noting is that both input and output parameters are nullable types. The next step is to add the assembly to the SQL Server database.



The syntax to do that is



   1: create assembly NullableTypes from




   2:  'C:\Users\Administrator\Documents\Visual Studio 2008\Projects\NullableTypesExample\NullableTypesExample\bin\Debug\NullableTypesExample.dll'


   3:  Go




Once the assembly is registered, you can now proceed to create your stored procedure pointing it to the managed code by executing the statement below




   1:  Create Proc dbo.SearchEmployee(@a bigint, @b smallint output)


   2:  as


   3:  EXTERNAL NAME NullableTypes.[StoredProcedures].SearchEmployee


   4:  GO




That is it!!! You are now all set to execute the stored procedure and check the results. For your reference, I am also giving below the statements to execute the procedure



 




   1:  declare @outvalue smallint


   2:  set @outvalue = 0


   3:  exec dbo.SearchEmployee 1,@outvalue output


   4:  select @outvalue






If I change the input value to null, null will be returned as output exhibiting support for Nullable Types.

Saturday, August 29, 2009

A Date with SQL Server 2008

Almost everybody who has worked a fair bit in SQL Server knows that the datetime data type in SQL Server is one of the most primitive. Infact, in a lot of applications I have seen, they don’t even see it worthy of being used, opting to use varchar instead. Their argument: If I am going to convert it into varchar anyways, then I might as well store it in the same format.

Hopefully, that will change with SQL Server 2008. DateTime datatype has been given special attention in the latest edition of SQL Server; so much so that I will stick my neck out and say that it is the only data type that has been enhanced!!! (FILESTREAM is not a data type, remember?). This post is an attempt to give you a preview of what the enhancements are in the DateTime datatypes.

In the previous versions of SQL Server, there were no separate datatypes for date and time. That has changed now. In SQL Server 2008, you have date and time datatypes that let you store only date or time. Apart from this, there is also the datetime2 and datetimeoffset. The datetime2 lets you store a wider range of dates. If you use datetime your minimum value for the year is 1/1/1753. The datetime2 datatype lets you store a wider range and is based on the ANSI standard. The datetimeoffset as you would have already guessed, helps you store dates for different regions. Some of the key points that you have to remember when using the above datatypes are

  • You cannot use mathematical functions or expressions with the new datetime2 datatype. Use DateAdd instead.
  • Try avoiding the format ‘dmy’. This is the only string format that produces different results with the old datetime and the new datetime2 format.
  • Most of the old t-sql functions work consistently with both the datetime and the datetime2 datatypes.
  • If you are using datetime2, use the SYSDATETIME function for more precision.
  • Though you can use the Datetimeoffset datatype, SQL Server 2008 does not support automatic support for daylight savings.
  • It does not also provide support for timezones, so the most effective way to use the offset is to store the timezone at which the date was entered.
  • Use the SWITCHOFFSET function of SQL Server to convert the offsets to the timezones.

Saturday, August 22, 2009

SQL Server 2008 FILESTREAM – Part – II

Having done the necessary set up for configuring FILESTREAM on a SQL Server instance in Part - I, we will now look at how to query a FILESTREAM column from .NET code and insert new files.

For this purpose, I have created one more table called UserMaster. This has the usual details of a user like the first name, last name and a column PhotoId which is a foreignkey to the ProductPhotoId that we created in the previous part.

Querying files or data from the FILESTREAM is not too different from how you would query and display data from an ordinary table. I first create a stored procedure to get the user details and the photo associated with each user. The stored procedure is as below

create proc dbo.GetUserDetails
as
begin
Select UM.UserId, UM.UserName, UM.FirstName, UM.LastName, UM.EmailAddress, PP.ProductPhotoId, PP.LargePhoto
from
UserMaster UM INNER JOIN ProductPhotoWithFileStream PP
On
PP.ProductPhotoId=UM.PhotoId
end

As you can see, there is nothing special with the above stored procedure. The next step is to display these photos in a Windows form. I have a DataGridView which is going to display the pics. The code for Form.cs is

   1: var connString = ConfigurationManager.ConnectionStrings["FileStreamConn"].ConnectionString;
   2: var query = "GetUserDetails";
   3: var daProducts = new SqlDataAdapter(query,connString);
   4:  
   5: productsGridView.DataSource = null;
   6: productsGridView.Refresh();
   7: var binding = new BindingSource()
   8: productsGridView.DataSource = binding;
   9:  
  10: // Populate a new data table and bind it to the BindingSource.
  11: var table = new DataTable();
  12: daProducts.Fill(table);
  13: binding.DataSource = table;
  14:  
  15: // Resize the DataGridView columns to fit the newly loaded content.
  16: productsGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
  17: productsGridView.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders);

Again, nothing fancy. Plain old-fashioned code. But good enough to query the files in the database and display it as shown below.


ImageDisplay


To insert a user, I create a form where the user will enter the details and select the picture associated with the user.

InsertForm

We will ignore the rest of the code in the form and concentrate on the Insert Button click. Below is the code for the complete button click event



   1: //1. Call the procedure to insert an empty value as photo and get transaction context
   2: var connString = ConfigurationManager.ConnectionStrings["FileStreamConn"].ConnectionString;
   3: var query = "GetUserDetails";
   4: string filePath = String.Empty;
   5: string selPhotoPath = txtFilePath.Text;
   6: SqlCommand daInsertCommand=null;
   7:  
   8: try
   9: {
  10:  
  11:     //1.1open a new connection
  12:     SqlConnection conn = new SqlConnection(connString);
  13:     conn.Open();
  14:  
  15:  
  16:     SqlTransaction tranPhoto = conn.BeginTransaction("photoInsert");
  17:  
  18:     //1.2 Execute the command to insert the photo and get the photo id
  19:     daInsertCommand = new SqlCommand(query,conn);
  20:     daInsertCommand.Transaction = tranPhoto;
  21:     var PhotoId = daInsertCommand.ExecuteScalar();
  22:  
  23:     //1.3 Get the Path Name for the newly created file.
  24:     query = "Select LargePhoto.PathName() from ProductPhotoWithFilestream where ProductPhotoId = " + PhotoId;
  25:  
  26:     daInsertCommand.CommandText = query;
  27:     var PhotoPath = daInsertCommand.ExecuteScalar();
  28:     if (!PhotoPath.Equals(DBNull.Value))
  29:     {
  30:         filePath = (string)PhotoPath;
  31:     }
  32:  
  33:     //1.4 Get the transaction context for writing to the file.
  34:     daInsertCommand.CommandText = "SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()";
  35:     var txContext = daInsertCommand.ExecuteScalar();
  36:     if (!txContext.Equals(DBNull.Value))
  37:     {
  38:         //convert the transaction into a bytearray
  39:         byte[] transContext = (byte[])txContext;
  40:         //create a photostream object to write
  41:         SqlFileStream photoStream = new SqlFileStream(filePath, transContext, System.IO.FileAccess.Write);
  42:  
  43:         //read the selected image as a byte array
  44:         byte[] imgByte = File.ReadAllBytes(selPhotoPath);
  45:  
  46:         //write to the sql filestream
  47:         photoStream.Write(imgByte, 0, imgByte.Length);
  48:  
  49:         //close the filestream and commit transaction
  50:         photoStream.Close();
  51:  
  52:  
  53:         //2. Insert the User record with the PhotoId
  54:         daInsertCommand.CommandText = "InsertUser";
  55:         daInsertCommand.CommandType = CommandType.StoredProcedure;
  56:         daInsertCommand.Parameters.Add("@FirstName", SqlDbType.VarChar, 10);
  57:         daInsertCommand.Parameters.Add("@LastName", SqlDbType.VarChar, 10);
  58:         daInsertCommand.Parameters.Add("@UserName", SqlDbType.VarChar, 20);
  59:         daInsertCommand.Parameters.Add("@emailAdd", SqlDbType.VarChar, 100);
  60:         daInsertCommand.Parameters.Add("@PhotoId", SqlDbType.Int, 32);
  61:  
  62:         daInsertCommand.Parameters[0].Value = txtFirstName.Text;
  63:         daInsertCommand.Parameters[1].Value = txtLastName.Text;
  64:         daInsertCommand.Parameters[2].Value = txtUserName.Text;
  65:         daInsertCommand.Parameters[3].Value = "test@add.com";
  66:         daInsertCommand.Parameters[4].Value = PhotoId;
  67:  
  68:         daInsertCommand.ExecuteNonQuery();
  69:  
  70:         daInsertCommand.Transaction.Commit();
  71:  
  72:     }
  73: }
  74: catch(Exception ex)
  75: {
  76:     daInsertCommand.Transaction.Rollback();
  77:     MessageBox.Show(ex.Message);
  78: }



I have tried and added comments so that the snippet makes sense but I will re-cap the steps to insert a new file. The first thing to do is to insert an empty string value into the FILESTREAM column. This is done so that the SQL Server creates a new file on the file system. Note that a null value does not create a file.

The next thing is to get the path of the new file created and wrap it around the same transaction. This is done between lines 24 and 35. Once we get the transaction context, then writing the file is like writing to any other file on the file system.

Also note the use of the SQLFileStream data type which is tightly integrated with the FILESTREAM attribute. The downside of the approach I have shown above is the number of round trips to the database. There are atleast three, one to insert the empty value into the FILESTREAM column, another one to get the path and the final trip to get the transaction context. Though I did read somewhere that this can now be reduced with the output clause I have not tried this yet. I will get around to that in a while and post an update to this post.

That concludes our two part post on the FILESTREAM attribute. Though it is easy to get excited by the ability of thee FILESTREAM attribute, there are as with a lot of other things, considerations that need to be taken into account when using this. I found the below links useful for further reading

Using FILESTREAM with Other SQL Server Features

FILESTREAM Storage in SQL Server 2008

To FILESTREAM or not to FILESTREAM... That is the question