The most interesting features in SQL Server 2008

clock August 25, 2008 23:11 by author Mohammad Mahdi Ramezanpour

Maybe some of you want to ask me: OK. SQL Server 2008 is the latest version of SQL Server but what's new in it?

Today I want to introduce you to some of top features available in SQL Server 2008. This is an screen shot of a SQL Server 2008 query. You can see some of new features you can use in the latest version of SQL Server:

scrn-SQL08

As you saw, there are some amazing features has been added to the new version. Here is a list of most interesting features that implemented in the latest version of SQL Server:

  • Increase the precision of storing and managing DATE and TIME information.

  • Store semi-structured and sparsely populated sets of data efficiently, using Sparse Columns.

  • New fully integrated Full-Text Indexes enable high-performance, scalable, and manageable Full-Text Indexing.

  • Create large User-Defined Types and User-Defined Aggregates greater than 8 KB.

  • Pass large amounts of data easily to functions or procedures using new Table-Value Parameters.

  • Perform multiple operations efficiently with the new MERGE command.

  • Model hierarchical data, such as org charts, or files and folders, using the new HierarchyID data type.

  • Build powerful location-aware applications, using SQL Server’s new standards-compliant spatial data types and spatial indexing capabilities.

  • Manage files and documents efficiently with full SQL Server security and transaction support, using the powerful new FILESTREAM data type.

  • Easily identify dependencies across objects and databases, using New Dependency Management.

  • Experience faster queries and reporting with Grouping Sets through powerful ANSI standards-compliant extensions to the GROUP BY clause.

  • Experience efficient, high-performance data access, using new Filtered Indexes for subsets of data.

  • Currently rated 1.3 by 3 people

    • Currently 1.333333/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5


    LINQ to SQL: How to execute command in a transaction

    clock August 23, 2008 22:28 by author Mohammad Mahdi Ramezanpour

    It may happen to everyone; sometimes you may want to execute your LINQ to SQL commands in one transaction like you do it in SQL Server as following:

     

    BEGIN TRANSACTION
     
    IF ([something happend])
    begin
        -- Your code is here
    end
    ELSE
    begin
        -- Restore to original
        ROLLBACK TRANSACTON
    end
     
    COMMIT TRANSACTION

    In this post I want to show how you can do it using LINQ to SQL:

    Create your LINQ to SQL project and write some code in order to do something ex.: Add a new record to a database. You should pass the following steps in order to manage transactions in LINQ to SQL:

    First, You must add a new reference named System.Transactions to your project:

    SelectingSytem_Transactions_Reference

    Then, you must create a new variable from System.Transactions.TransactionScope like this:

     

    using (TransactionScope ts = new TransactionScope())
    {
         // Your code comes here.
    }

    After that you must add your insert code between using tags:

    using (TransactionScope ts = new TransactionScope())
                {
                    try
                    {
                        Post p = new Post();
                        p.title = title;
                        p.keywords = keywords;
                        p.shortDesc = shortDesc;
                        p.content = content;
                        p.startRate = Convert.ToByte(startRate);
                        p.enableComments = enableComments;
                        p.usersCanRate = usersCanRate;
                        p.createDate = DateTime.Now;
                        p.lastModifyDate = DateTime.Now;
                        c.Posts.InsertOnSubmit(p);
                        c.SubmitChanges();
                        
                        Guid postId = p.postId;
     
                        foreach (var author in authors)
                        {
                            Posts_AddAuthorRelation(postId, author.AuthorID);
                        }
     
                        foreach (var category in categories)
                        {
                            Posts_AddCategoryRelation(postId, category.CategoryID);
                        }
     
                        foreach (var source in sources)
                        {
                            Posts_AddSourceRelation(postId, source.SourceID);
                        }
     
                        foreach (var media in medias)
                        {
                            Posts_AddMediaRelation(postId, media.MediaID);
                        }
                    }
                    catch
                    {
                        Transaction.Current.Rollback();
                    }
                }

    As you can see I put a try...catch statements to my code. In try section I just wrote my insert code. If there is any error with my database or something. It will goes to my catch block.
    Because I insert to more than one table, I should delete all inserted tables if there is any exception(s).

    So you must use System.Transactions.Transaction.Rollback() method in order roll it back like SQL Server's ROLLBACK TRANSACTION command that we talked about it above.

    With System.Transactions, you can manage your LINQ to SQL commands in transactions.

    Be the first to rate this post

    • Currently 0/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5


    Microsoft SQL Server 2008 Is now available for download

    clock August 12, 2008 18:37 by author Mohammad Mahdi Ramezanpour

    I was waiting a lot for this realase of SQL Server and finally it has been released today. Lets take a look at product overview published from Microsoft official website:

    Your Data, Any Place, Any Time

    SQL Server 2008 delivers on Microsoft’s Data Platform vision by helping your organization manage any data, any place, any time. It enables you to store data from structured, semi-structured, and unstructured documents, such as images and music, directly within the database. SQL Server 2008 delivers a rich set of integrated services that enable you to do more with your data such as query, search, synchronize, report, and analyze. Your data can be stored and accessed in your largest servers within the data center all the way down to desktops and mobile devices, enabling you to have control over your data no matter where it is stored.

    SQL Server 2008 enables you to consume your data within custom applications developed using Microsoft .NET and Visual Studio and within your service-oriented architecture (SOA) and business process through Microsoft BizTalk Server while information workers can access data directly in the tools they use every day, such as the 2007 Microsoft Office system. SQL Server 2008 delivers a trusted, productive, and intelligent data platform for all your data needs.

    SQL Server 2008 New Features

    TRUSTED

    SQL Server provides the highest levels of security, reliability, and scalability for your business-critical applications.

  • Transparent Data Encryption

    Enable encryption of an entire database, data files, or log files, without the need for application changes. Benefits of this include: Search encrypted data using both range and fuzzy searches, search secure data from unauthorized users, and data encryption without any required changes in existing applications.

  • Extensible Key Management

    SQL Server 2005 provides a comprehensive solution for encryption and key management. SQL Server 2008 delivers an excellent solution to this growing need by supporting third-party key management and HSM products.

  • Auditing

    Create and manage auditing via DDL, while simplifying compliance by providing more comprehensive data auditing. This enables organizations to answer common questions, such as, "What data was retrieved?"

  • Enhanced Database Mirroring

    SQL Server 2008 builds on SQL Server 2005 by providing a more reliable platform that has enhanced database mirroring, including automatic page repair, improved performance, and enhanced supportability.

  • Automatic Recovery of Data Pages

    SQL Server 2008 enables the principal and mirror machines to transparently recover from 823/824 types of data page errors by requesting a fresh copy of the suspect page from the mirroring partner transparently to end users and applications.

  • Log Stream Compression

    Database mirroring requires data transmissions between the participants of the mirroring implementations. With SQL Server 2008, compression of the outgoing log stream between the participants delivers optimal performance and minimizes the network bandwidth used by database mirroring.

  • Resource Governor

    Provide a consistent and predictable response to end users with the introduction of Resource Governor, allowing organizations to define resource limits and priorities for different workloads, which enable concurrent workloads to provide consistent performance to their end users.

  • Predictable Query Performance

    Enable greater query performance stability and predictability by providing functionality to lock down query plans, enabling organizations to promote stable query plans across hardware server replacements, server upgrades, and production deployments.

  • Data Compression

    Enable data to be stored more effectively, and reduce the storage requirements for your data. Data compression also provides significant performance improvements for large I/O bound workloads, like data warehousing.

  • Hot Add CPU

    Dynamically scale a database on demand by allowing CPU resources to be added to SQL Server 2008 on supported hardware platforms without forcing any downtime on applications. Note that SQL Server already supports the ability to add memory resources online.

    PRODUCTIVE

    To take advantage of new opportunities in today's fast-moving business world, companies need the ability to create and deploy data-driven solutions quickly. SQL Server 2008 reduces time and cost of management and development of applications.

  • Policy-Based Management

    Policy-Based Management is a policy-based system for managing one or more instances of SQL Server 2008. Use this with SQL Server Management Studio to create policies that manage entities on the server, such as the instance of SQL Server, databases, and other SQL Server objects.

  • Streamlined Installation

    SQL Server 2008 introduces significant improvements to the service life cycle for SQL Server through the re-engineering of the installation, setup, and configuration architecture. These improvements separate the installation of the physical bits on the hardware from the configuration of the SQL Server software, enabling organizations and software partners to provide recommended installation configurations.

  • Performance Data Collection

    Performance tuning and troubleshooting are time-consuming tasks for the administrator. To provide actionable performance insights to administrators, SQL Server 2008 includes more extensive performance data collection, a new centralized data repository for storing performance data, and new tools for reporting and monitoring.

  • DATE/TIME

    SQL Server 2008 introduces new date and time data types:

    • DATE—A date-only type

    • TIME—A time-only type

    • DATETIMEOFFSET—A time-zone-aware datetime type

    • DATETIME2—A datetime type with larger fractional seconds and year range than the existing DATETIME type

    The new data types enable applications to have separate data and time types while providing large data ranges or user defined precision for time values.

  • HIERARCHY ID

    Enable database applications to model tree structures in a more efficient way than currently possible. New system type HierarchyId can store values that represent nodes in a hierarchy tree. This new type will be implemented as a CLR UDT, and will expose several efficient and useful built-in methods for creating and operating on hierarchy nodes with a flexible programming model.

  • FILESTREAM Data

    Allow large binary data to be stored directly in an NTFS file system, while preserving an integral part of the database and maintaining transactional consistency. Enable the scale-out of large binary data traditionally managed by the database to be stored outside the database on more cost-effective storage without compromise.

  • Integrated Full Text Search

    Integrated Full Text Search makes the transition between Text Search and relational data seamless, while enabling users to use the Text Indexes to perform high-speed text searches on large text columns.

  • Sparse Columns

    NULL data consumes no physical space, providing a highly efficient way of managing empty data in a database. For example, Sparse Columns allows object models that typically have numerous null values to be stored in a SQL Server 2005 database without experiencing large space costs.

  • Large User-Defined Types

    SQL Server 2008 eliminates the 8-KB limit for User-Defined Types (UDTs), allowing users to dramatically expand the size of their UDTs.

  • Spatial Data Types

    Build spatial capabilities into your applications by using the support for spatial data.

    • Implement Round Earth solutions with the geography data type. Use latitude and longitude coordinates to define areas on the Earth's surface.

    • Implement Flat Earth solutions with the geometry data type. Store polygons, points, and lines that are associated with projected planar surfaces and naturally planar data, such as interior spaces.

  • INTELLIGENT

    SQL Server 2008 provides a comprehensive platform, delivering intelligence where your users want it.

  • Backup Compression

    Keeping disk-based backups online is expensive and time-consuming. With SQL Server 2008 backup compression, less storage is required to keep backups online, and backups run significantly faster since less disk I/O is required.

  • Partitioned Table Parallelism

    Partitions enable organizations to manage large growing tables more effectively by transparently breaking them into manageable blocks of data. SQL Server 2008 builds on the advances of partitioning in SQL Server 2005 by improving the performance on large partitioned tables.

  • Star Join Query Optimizations

    SQL Server 2008 provides improved query performance for common data warehouse scenarios. Star Join Query optimizations reduce query response time by recognizing data warehouse join patterns.

  • Grouping Sets

    Grouping Sets is an extension to the GROUP BY clause that lets users define multiple groupings in the same query. Grouping Sets produces a single result set that is equivalent to a UNION ALL of differently grouped rows, making aggregation querying and reporting easier and faster.

  • Change Data Capture

    With Change Data Capture, changes are captured and placed in change tables. It captures complete content of changes, maintains cross-table consistency, and even works across schema changes. This enables organizations to integrate the latest information into the data warehouse.

  • MERGE SQL Statement

    With the introduction of the MERGE SQL Statement, developers can more effectively handle common data warehousing scenarios, like checking whether a row exists, and then executing an insert or update.

  • SQL Server Integration Services (SSIS) Pipeline Improvements

    Data Integration packages can now scale more effectively, making use of available resources and managing the largest enterprise-scale workloads. The new design improves the scalability of runtime into multiple processors.

  • SQL Server Integration Services (SSIS) Persistent Lookups

    The need to perform lookups is one of the most common ETL operations. This is especially prevalent in data warehousing, where fact records need to use lookups to transform business keys to their corresponding surrogates. SSIS increases the performance of lookups to support the largest tables.

  • Analysis Scale and Performance

    SQL Server 2008 drives broader analysis with enhanced analytical capabilities and with more complex computations and aggregations. New cube design tools help users streamline the development of the analysis infrastructure enabling them to build solutions for optimized performance.

  • Block Computations

    Block Computations provides a significant improvement in processing performance enabling users to increase the depth of their hierarchies and complexity of the computations.

  • Writeback

    New MOLAP enabled writeback capabilities in SQL Server 2008 Analysis Services removes the need to query ROLAP partitions. This provides users with enhanced writeback scenarios from within analytical applications without sacrificing the traditional OLAP performance.

  • Enterprise Reporting Engine

    Reports can easily be delivered throughout the organization, both internally and externally, with simplified deployment and configuration. This enables users to easily create and share reports of any size and complexity.

  • Internet Report Deployment

    Customers and suppliers can effortlessly be reached by deploying reports over the Internet.

  • Manage Reporting Infrastructure

    Increase supportability and the ability to control server behavior with memory management, infrastructure consolidation, and easier configuration through a centralized store and API for all configuration settings.

  • Report Builder Enhancements

    Easily build ad-hoc and author reports with any structure through Report Designer.

  • Built-In Forms Authentication

    Built-in forms authentication enables users to easily switch between Windows and Forms.

  • Report Server Application Embedding

    Report Server application embedding enables the URLs in reports and subscriptions to point back to front-end applications.

  • Microsoft Office Integration

    SQL Server 2008 provides new Word rendering that enables users to consume reports directly from within Microsoft Office Word. In addition, the existing Excel renderer has been greatly enhanced to accommodate the support of features, like nested data regions, sub-reports, as well as merged cell improvements. This lets users maintain layout fidelity and improves the overall consumption of reports from Microsoft Office applications.

  • Predictive Analysis

    SQL Server Analysis Services continues to deliver advanced data mining technologies. Better Time Series support extends forecasting capabilities. Enhanced Mining Structures deliver more flexibility to perform focused analysis through filtering as well as to deliver complete information in reports beyond the scope of the mining model. New cross-validation enables confirmation of both accuracy and stability for results that you can trust. Furthermore, the new features delivered with SQL Server 2008 Data Mining Add-ins for Office 2007 empower every user in the organization with even more actionable insight at the desktop.

  •  For more information about this release and download it, you can check out Microsoft SQL Server 2008 Home Page

     By the way I have to thanks a lot from Microsoft for releasing this version of SQL Server.

    Be the first to rate this post

    • Currently 0/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5


    What Is a Transaction?

    clock August 2, 2008 02:31 by author Mohammad Mahdi Ramezanpour

    Source: Microsoft SQL Server 2005 Programming - Microsoft Press

    A transaction is a single operation or set of operations that succeed or fail together, thereby ensuring consistency of data should unforeseen circumstances arise. An example might be a financial transaction. For example, let's say you buy a car. The single transaction of buying a car consists of three distinct operations:

    1. You select a car.

    2. You pay for it.

    3. You drive the car off the lot.

    Skipping any of these steps could cause major angst to one or more of the parties involved. This is a simple example of a set of steps that must always occur together in a consistent manner.

    Transactions allow us to ensure consistency in our data through four basic principles. These principles provide a set of rules that must be followed in order for our transaction to succeed. The four principles help ensure that the state of our data is atomic, consistent, isolated, and durable regardless of the success or failure of the transaction. These properties are covered in the next topic.

    Understanding the ACID Properties

    Consider the transaction of going to an ATM and withdrawing $100 from your bank account. The data for this transaction can be easily represented in a database as a table with two columns, one holding your AccountID and the other holding your AccountBalance.

    To begin with, your account balance is $100, so after withdrawing $100, your updated balance should be zero. Also, it makes logical sense that before the money can be disbursed, the system must ensure that you have the funds available in your account. What this means in database terms is that two database queries must be run in this transaction. The first query checks the account balance.

    SELECT AccountBalance FROM Account WHERE AccountID = @AccountID

    If the query returns an AccountBalance value greater than or equal to the requested withdrawal, you can perform the operation of withdrawing cash.

    After withdrawing the cash, you must update the account record with the updated balance. To do so, you run an UPDATE query.

    UPDATE AccountSET AccountBalance = AccountBalance 100WHERE AccountID = @AccountID

    The three distinct operations in this transaction are two database queries and one operation of withdrawing cash. All three must succeed or fail together in an atomic manner, or the transaction should not be considered complete. Atomicity is the first ACID property.

    Now let's change the nature of the transaction a bit. Let's say the original account balance is $150 and that within the same transaction, the user requests to withdraw $100 and to transfer another $75 to a second account. The first update query will succeed, changing the account balance to $150 $100 = $50. But the second operation will fail because there won't be enough money left in the account to transfer the $75. You therefore need a way to undo the cash transfer and withdrawal steps and return the database to its original state. You cannot leave the database midway through a transaction because it may be in an inconsistent state. In a real-world scenario, you would not normally wrap a withdrawal and a transfer in the same transaction in the event that you want at least one of the operations to be successful. The point here is to show how the data can end up in an inconsistent state between two operations. Rolling back operations that cannot be completed in this manner demonstrates the second ACID property, consistency.

    Let's say the two operationscash withdrawal and cash transferare broken up into two distinct transactions instead of one but that they happen to run simultaneously, or concurrently. Each transaction will have to check the current balance. They will do this by attempting to execute a query like this:

    SELECT AccountBalance FROM Account WHERE AccountID = @AccountID

    Unless your system has explicit checks blocking concurrent reads, both transactions will get the same result: $150. Thus they will both assume that the account has enough funds for the transaction. One transaction will disburse $100, and the other will transfer $75. But this will result in an overall deduction of $100 + $75 = $175, even though the account actually has only $150. In a well-designed system, the transactions must be isolated from each other to prevent what is known as "dirty reads." A dirty read happens when data is read at one point in a transition state and the "read" doesn't reflect the data's true state at the end of the current operation. This brings us to the third ACID property, isolation.

    Isolation means that other transactions attempting to request a common resource will be blocked. Blocking, in turn, seriously affects the response times of your application. As it turns out, you'll often want to relax this blocking behavior to suit your application architecture. This involves using isolation levels, which we'll discuss later in the chapter.

    Finally, when you have successfully completed all your operations within a transaction, you don't want to lose the changes made. In other words, system failures must not affect the transactional integrity of your operations. This brings us to the fourth ACID property, durability.

    Let's review the four ACID properties again before we continue:

    • Atomicity Operations succeed or fail together. Unless all steps succeed, the transaction cannot be considered complete.

    • Consistency Operations leave the database in a consistent state. The transaction takes the underlying database from one stable state to another, with no rules violated before the beginning or after the end of the transaction.

    • Isolation Every transaction is an independent entity. One transaction will not affect any other transaction that is running concurrently.

    • Durability Every transaction is persisted on a reliable medium that cannot be undone by system failures. Also, if a system failure occurs in the middle of a transaction, the completed steps must be undone by the system or the uncompleted steps must be executed to finish the transaction. This typically happens by use of a log that can be played back to return the system to a consistent state.

    Currently rated 5.0 by 1 people

    • Currently 5/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5


    LINQ to SQL: How to use SQL "IN" keyword in LINQ?

    clock July 31, 2008 01:38 by author Mohammad Mahdi Ramezanpour

    If you have been worked with T-SQL, You know that we have an IN keyword in our WHERE clause like the following instance:

    SELECT * FROM MyTable WHERE ID IN (1, 2, 3)

    In the example above, I selected a table from my database named "MyTable" and then select rows that the ID column of each row is equal to 1, 2 and 3. If rows are exists so the select statement should return 3 results.

    When you're working with .NET framework 3.5, You may need to do such a thing using LINQ to SQL. In this post I'll show you how to do that.

    Before we get started, lets review some simple LINQ commands and basics:

    • In order to start using LINQ to SQL, You have to create a new item named LINQ to SQL Class by right click on your project in solution explorer, point to add menu and select new item as shown below:

     AddNewItem

    • In the new item windows select LINQ to SQL class and name it SampleDb:

     SelectLinqtoSqlClass

    • Now it's time to add some SQL tables from our SQL Server Database by drag them from Server Explorer (Available in View menu) and drop them to our LINQ to SQL Class designer. When you do such a thing, Visual Studio adds some classes with properties and methods to your project automatically.

    AddSomeTables 

    • We can add some code in order to access our data. First you have to declare a new variable from our LINQ to SQL class. By default, the name of our LINQ to SQL class is YouClassName + DataContext. So here it is:

    private SampleDbDataContext db = new SampleDbDataContext();

    You can select, insert, update and delete rows from your selected table(s). What we're looking for right now is to select 4 specific rows from our table to simulate SQL "IN" keyword. In order to do this, have to create an array of your selected IDs. In this case I want to select rows with IDs (1, 2, 3); So just create an integer array as following:

    int[] MySelectedRows = {1, 2, 3} ;

    Now lets write some codes in order to select some columns from our table:

    var MyData = (from data in db.Mails
                              select data);

    With the code above, you can select all rows in Mails table. Now we have to specify to select only rows with IDs 1, 2 and 3 so we must add a where clause to our select statement:

    var MyData = (from data in db.Mails
                              where data.MailID == Convert.ToInt32(MySelectedRow)
                              select data);

    Currently rated 4.0 by 3 people

    • Currently 4/5 Stars.
    • 1
    • 2
    • 3
    • 4
    • 5


    Welcome


    Mohammad Mahdi Ramezanpour
    Welcome to my website. Hope you can get something useful here. For more information about me and ways you can contact, please use site menu.

    Main Menu

    Sign in