Thursday, November 8, 2012

Table Data - XML

Last week I was searching for a solution to generate a complicated XML straight away out of the SQL Server. Actually, I had huge data scattered in few tables that I wanted to map to an XML with several attributes n elements with multiples levels of hierarchy, I was trying to generate this XML with the FOR XML Explicit mode. Doing things with this was really really complicated n terrible. So, I started to look around for new XML features introduced with SQL Server 2005 (as I was using SQL Server 2005 for this).
While browsing through MSDN pages I came around this new mode 'FOR XML PATH' introduced with SQL Server 2005. This is really a cool feature and gives you the ability to generate the complex XML with a greater ease, with this feature I was safe home and was able to generate the XML in desired format with a great ease. Thank God!!!
The new PATH mode allows you to use an XPath-like syntax as a column name which then is mapped into an attribute or element or sub element of the XML as per you specify and you can have multiple level of hierarchy and can mix elements n attributes. The problem with FOR XML AUTO n RAW modes with SQL Server 2000 was that you can have either the attributes or the elements but not both. If you want to have mixed content in XML you have to go for XML Explicit mode which was too complex n for generating hierarchy you have to Union lot of SQL Statements so, it sometimes, used to correctly called as the "query from hell".
With the Introduction of the FOR XML Path Mode things can be as easy as following:
SELECT CustomerID as "@CustomerID",
CompanyName,
Address as "address/street",
City as "address/city",
Region as "address/region",
PostalCode as "address/zip",
Country as "address/country",
ContactName as "contact/name",
ContactTitle as "contact/title",
Phone as "contact/phone",
Fax as "contact/fax"
FROM Customers
FOR XML PATH('Customer')

This will give you the following result:
<Customer CustomerID="ALFKI">
<CompanyName>Alfreds Futterkiste</CompanyName>
<address>
<street>Obere Str. 57</street>
<city>Berlin</city>
<zip>12209</zip>
<country>Germany</country>
</address>
<contact>
<name>Maria Anders</name>
<title>Sales Representative</title>
<phone>030-0074321</phone>
<fax>030-0076545</fax>
</contact>
</Customer>
...

If you analyze down the results you can figure out that the column you specify as "@" are resulted in attributes e.g. customer ID, the column with no alias is resulted in element e.g. company name. Now the columns which you want to be embedded in some tag can be also generated using syntax 'element1/element2' e.g. for city column we have specified 'address/city'. It is this simple to generate the mixed kind of XML with this new mode.
There's a lot to it, lot many features and options available, for complete details visit the following links:
http://msdn2.microsoft.com/en-us/library/ms345137.aspx
http://sqljunkies.com/WebLog/mrys/archive/2004/02/19/1208.aspx
Hope you get benefited with this.

Thursday, October 25, 2012

Summary Log after SQL-Server Installation

View and Read SQL Server Setup Log Files

Each execution of Setup creates log files are created with a new timestamped log folder at %programfiles%\Microsoft SQL Server\110\Setup Bootstrap\Log\. The time-stamped log folder name format is YYYYMMDD_hhmmss. When Setup is run in an unattended mode, the logs are created at % temp%\sqlsetup*.log. All files in the logs folder are archived into the Log*.cab file in their respective log folder.
A typical Setup request goes through three execution phases:
  1. Global rules text
  2. Component update
  3. User-requested action
In each phase, Setup generates detail and summary logs with additional logs created as appropriate. Setup is called at least three times per user-requested Setup action.
Datastore files contain a snapshot of the state of all configuration objects being tracked by the Setup process, and are useful for troubleshooting configuration errors. XML file dumps are created for datastore objects for each execution phase. They are saved in their own log subfolder under the time-stamped log folder, as follows:
  • Datastore_GlobalRules
  • Datastore_ComponentUpdated
  • Datastore
The following sections describe SQL Server Setup log files.

Overview

This file shows the SQL Server components that were detected during Setup, the operating system environment, command-line parameter values if they are specified, and the overall status of each MSI/MSP that was executed.
The log is organized into the following sections:
  • An overall summary of the execution
  • Properties and the configuration of the computer where SQL Server Setup was run
  • SQL Server product features previously installed on the computer
  • Description of the installation version and installation package properties
  • Runtime input settings that are provided during install
  • Location of the configuration file
  • Details of the execution results
  • Global rules
  • Rules specific to the installation scenario
  • Failed rules
  • Location of the rules report file

Location

It is located at %programfiles%\Microsoft SQL Server\110\Setup Bootstrap\Log\.
To find errors in the summary text file, search the file by using the "error" or "failed" keywords.

Overview

The summary_engine base file is similar to the summary file and is generated during the main workflow.

Location

It is located at %programfiles%\Microsoft SQL Server\110\Setup Bootstrap\Log\<YYYYMMDD_HHMM>\.

Overview

The component update summary log file is similar to the summary file and is generated during the component update workflow.

Location

It is located at %programfiles%\Microsoft SQL Server\110\Setup Bootstrap\Log\<YYYYMMDD_HHMM>\.

Overview

The global rules summary log file is similar to the summary file generated during the global rules workflow.

Location

It is located at %programfiles%\Microsoft SQL Server\110\Setup Bootstrap\Log\<YYYYMMDD_HHMM>\.

Overview

Detail.txt is generated for the main workflow such as install or upgrade, and provides the details of the execution. The logs in the file are generated based on the time when each action for the installation was invoked, and show the order in which the actions were executed, and their dependencies.

Location

It is located at %programfiles%\Microsoft SQL Server\110\Setup
Bootstrap\Log\<YYYYMMDD_HHMM>\Detail.txt.
If an error occurs during the Setup process, the exception or error are logged at the end of this file. To find the errors in this file, first examine the end of the file followed by a search of the file for the “error” or “exception” keywords.

Overview

The Detail_ComponentUpdate.txt file is generated for the component update workflow and is similar to Detail.txt.

Location

It is located at %programfiles%\Microsoft SQL Server\110\Setup Bootstrap\Log\<YYYYMMDD_HHMM>\.

Overview

Detail_GlobalRules.txt is generated for the global rules execution and is similar to Detail.txt.

Location

It is located at %programfiles%\Microsoft SQL Server\110\Setup Bootstrap\Log\<YYYYMMDD_HHMM>\.

Overview

The MSI log files provide details of the installation package process. They are generated by the MSIEXEC during the installation of the specified package.
Types of MSI log files:
  • <Feature>_<Architecture>_<Interation>.log
  • <Feature>_<Architecture>_<Language>_<Interation>.log
  • <Feature>_<Architecture>_<Interation>_<workflow>.log

Location

The MSI log files are located at %programfiles%\Microsoft SQL Server\110\Setup Bootstrap\Log\<YYYYMMDD_HHMM>\<Name>.log.
At the end of the file is a summary of the execution which includes the success or failure status and properties. To find the error in the MSI file, search for “value 3” and usually the errors can be found close to the string.

Overview

The configuration file contains the input settings that are provided during installation. It can be used to restart the installation without having to enter the settings manually. However, passwords for the accounts, PID, and some parameters are not saved in the configuration file. The settings can be either added to the file or provided by using the command line or the Setup user interface. For more information, see Install SQL Server 2012 using a Configuration File(http://go.microsoft.com/fwlink/?LinkId=231296).

Location

It is located at %programfiles%\Microsoft SQL Server\110\Setup Bootstrap\Log\<YYYYMMDD_HHMM>\.

Overview

The system configuration check report contains a short description for each executed rule, and the execution status.

Location

It is located at %programfiles%\Microsoft SQL Server\110\Setup Bootstrap\Log\<YYYYMMDD_HHMM>\.

Wednesday, October 17, 2012

Recovering unsaved or modified scripts


Let’s face it we have all spent countless hours developing and/or polishing up our sql scripts deep into the wee hours of the night to the point of near exhaustion. We rise early the next morning (or a few hours later in most cases), pour a cup of coffee and head over to our laptop to find that our system rebooted. Then reality sinks in and you suddenly realize that you didn’t save anything before calling it a night. Now you’re thinking “[enter swear phrase of choice here]“!
Don’t panic…
Typically when you re-open SQL Server Management Studio you’re prompted with a nice little screen that politely asks if you would like to recover the selected files or queries. Which is extremely helpful, but what happens when you don’t get that prompt, what then?
The answer is easy enough and may require you to change your folder options to show hidden files and folders. In the event you find yourself in a similar situation simply navigate to (assuming you are running Windows 7) 
C:\Users\”[your username goes here]“\AppData\Local\Temp\ 
or 
C:\Users\<UserName>\Documents\SQL Server Management Studio\Backup Files\Solution1   
and look for files similarly named like the ones illustrated below.


Monday, August 6, 2012

INTRODUCING SQL SERVER 2012 SNIPPETS

INTRODUCING SQL SERVER 2012 SNIPPETS

Author: Saleem Hakani (Microsoft Corporation)

SQL Server 2012 introduces a new feature called T-SQL Snippets. T-SQL Snippets allow you to quickly build T-SQL statements without having to remember the commands or its syntax. This feature can potentially help with reduced development time and in increased productivity for developers and DBA’s. Snippet templates in SQL Server 2012 are based on XML with predefined fields and values. When you use T-SQL snippet, these fields are highlighted and the user can tab through each fields and change the values as required.

Imagine a series of commands that you always use when creating a Trigger or a Table or a Stored Procedure or even a SELECT statement. You can now reduce the amount of time and code you would write by implementing T-SQL Snippets in SQL Server 2012.

Snippets are categorized for ease of use so that the user can see and use various snippets based on the category.

        SQL Server 2012 introduces three types of snippets:

DEFAULT SNIPPETS
(aka: Expansion Snippets)
SURROUND SNIPPETS
CUSTOM SNPPETS
These are code templates for various T-SQL commands that you can quickly insert into your T-SQL code when creating tables, stored procedures, triggers, etc.
These are code templates that allow you to implement code construct like Begin End, If, While, etc.
Custom Snippets allow you to create your own Snippet that can appear with the Snippet menu when invoked.



CREATING A CUSTOM SNIPPET
Let’s now look at how to create a custom Snippet and add it to the Snippet menu. Creating and using a Snippet is a 3 steps process:

1.       Create a Snippet using XML
2.       Register the Snippet in SSMS
3.       Invoke the Snippet when using Query Editor

NOTE: By default, all T-SQL Snippets are stored under the following folder and are saved as .snippet files: 
“C:\Program Files\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\SQL\Snippets\1033”


STEP1: CREATE A T-SQL SNIPPET FILE USING XML
In the example below, we will create a snippet that can be used to write Select statement for any table and would allow the use of CASE statement for an equality check on a column.

CASE_END.SNIPPET File
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0">
<Header>
<Title>Case-End</Title>
<Description> Insert Case...End Construct. </Description>
<Author> Saleem Hakani (Microsoft Corporation) </Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="SQL">
<![CDATA[
Select <Column_Name1>, <Column_Name2>, <Column_Name3>, <Column_Name4>=
        CASE <Column_Name4>
           WHEN '<value>' THEN '<Result>'
           WHEN '<value>' THEN '<Result>'
           WHEN '<value>' THEN '<Result>'
                   WHEN '<value>' THEN '<Result>'
           ELSE 'Value not found'
        END,
<Column_Name5>, <Column_Name6>
From <Table_Name>
Go
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
STEP2: REGISTER THE SNPPET WTH SQL SERVER MANAGEMENT STUDIO
Once the above file is created, you can now use the Code Snippets Manager to register the snippet with SQL Server Management Studio. You can either add a new folder based on the snippet category or import individual snippets to the My Code Snippets folder.

To Add a Snippet Folder:
1.       Launch SQL Server Management Studio
2.       Select “Tools” from the menu items and Click on “Code Snippets Manager” (This will launch the Snippet Manager)
3.       Click on the “Add” button
4.       Browse to the folder containing CASE_END.Snippet file, and click on the Select Folder button.

Next step is to import the Snippet in to SQL Server Management Studio:

To Import a Snippet:
1.       Launch SQL Server Management Studio
2.       Select “Tools” from the menu items and click on “Code Snippets Manager”
3.       Click on the “Import” button at the bottom
4.       Browse to the folder containing CASE_END.snippet file and select CASE_End.snippet file by clicking on it and then click on “Open” button.

STEP3: INVOKE OR INSERT T-SQL SNIPPET FROM QUERY EDITOR
You now have a snippet created called CASE_END that can be invoked by using the shortcut key from the query editor by pressing “CTRL + K X” and then by selecting the category folder in which you created the snippet.

Alternatively, you can right click on the context menu in query editor and select “Insert Snippet…”

There’s another way of invoking a Snippet which I find rather easy to invoke is by right clicking on the context menu in the query editor which will present you with various Snippet Options.


Using the above steps, you can create T-SQL code snippet and register it with SQL Server Management Studio. You can also create complex snippets of various regular tasks and make your SQL Server life easy.

Tuesday, July 31, 2012

Introducing SEQUENCE For Your IDENTITY Needs

There are many applications that require incremental numbers for maintaining unique rows in a table. For several years, we’ve been using IDENTITY() column as our primary option to generate incremental numbers for unique records or for Primary key values and it has been the first choice for developers. You’ve tried IDENTITY() and now try the new feature added in SQL Server 2012 and experience the difference.

SQL Server 2012 introduces a brand new schema bound object called SEQUENCE. Sequence generates numeric values based on the specification of a SEQUENCE object. You can generate numeric values in either ascending or descending order and they can be independent of tables unlike IDENTITY columns.

Here’s the syntax on how you can create a SEQUENCE using various options.


CREATE SEQUENCE SYNTAX
CREATE SEQUENCE [schema_name . ] sequence_name
    [ AS [ built_in_integer_type | user-defined_integer_type ] ]
    [ START WITH <constant> ]
    [ INCREMENT BY <constant> ]
    [ { MINVALUE [ <constant> ] } | { NO MINVALUE } ]
    [ { MAXVALUE [ <constant> ] } | { NO MAXVALUE } ]
    [ CYCLE | { NO CYCLE } ]
    [ { CACHE [ <constant> ] } | { NO CACHE } ]
    [ ; ]


Let’s now take a look at an example on how to use SEQUENCE in SQL Server 2012.

In the below example, we will look at:
§  Creating a sequence
§  Create a sample Item table
§  Use SEQUENCE when inserting data in a table
§  Query Item table
§  Alter or delete SEQUENCE from SQL Server

In this step, we will create a new object called MYSEQUENCE1 that will start with a value of 1 and increment it’s value by 1.


STEP 1 - CREATING A SEQUENCE CALLED MYSEQUENCE1

CREATE SEQUENCE ITEMIDSEQUENCE
      START WITH 1
      INCREMENT BY 1;



In this step, we will create a sample ITEM table with just two columns.


STEP 2 - CREATING ITEM TABLE

CREATE TABLE ITEM
(
ITEMNO INT,
ITEMNAME VARCHAR(50)
);
GO



In this step, we will insert data in the ITEM table by leveraging the newly create MYSEQUENCE1 which will automatically insert and increment the values of MYSEQUENCE1 by 1.


STEP 3 – USING SEQUENCE FOR INSERTING DATA IN A TABLE

INSERT INTO ITEM VALUES (NEXT VALUE FOR ITEMIDSEQUENCE, 'MANGO');
INSERT INTO ITEM VALUES (NEXT VALUE FOR ITEMIDSEQUENCE, 'APPLE');
INSERT INTO ITEM VALUES (NEXT VALUE FOR ITEMIDSEQUENCE, 'BANANA');
INSERT INTO ITEM VALUES (NEXT VALUE FOR ITEMIDSEQUENCE, 'ORANGE');
INSERT INTO ITEM VALUES (NEXT VALUE FOR ITEMIDSEQUENCE, 'GRAPES');
GO



In this step, we will query the ITEM table to review the data in the ITEM table. Notice that the ITEMNO column in the ITEM table has sequential numbers that were auto-inserted using ITEMIDSEQUENCE sequence.


STEP 4 – QUERYING DATA FROM A TABLE USING SEQUENCE

SELECT * FROM ITEM

YOU’LL SEEE THE FOLLOWING RESULT SET.

ITEMNO
ITEMNAME
1
MANGO
2
APPLE
3
BANANA
4
ORANGE
5
GRAPES




In this step, we will look at Altering, Deleting & Querying Sequences:


ALTER, DELETE, AND  QUERY SEQUENCES

To delete a sequence:
DROP SEQUENCE ITEMIDSEQUENCE

To alter a sequence:
ALTER SEQUENCE ITEMIDSEQUENCE
      RESTART WITH 900
      INCREMENT BY 1
  GO

To query the next value of Sequence for a particular SEQUENCE object:
SELECT NEXT VALUE FOR ITEMIDSEQUENCE

To query all sequences available in a database, you can use the below query:
SELECT * FROM SYS.SEQUENCES






THINGS TO KEEP IN MIND:

§  Sequence values are not automatically protected after insertion in to a table. You should use Update Trigger on the table to prevent sequence values from being changed.

§  Sequences does not automatically enforce uniqueness for sequence values. You should create unique index on the Sequence column to enforce uniqueness.

§  If you have created a sequence for example assigns values 1 through 100, and if the rows in the table grows beyond 100 rows, then Sequence would start assigning values 1 through 100 again.

§  By default, if you do not specify data type for a sequence, BIGINT data type is used.  Keep in mind that you can create sequence that are of any integer data type.