29.2.12

Insert XML data into SQL Server


Read XML file and insert into SQL Server:

Here is the best way of stroring XML data into SQL Server. Option of storing the file in filestream data type is a nice feature.

 Hey forgot to share some information. Last week, I've tried storing the data into the system using file stream data type. Tried a mechanism of storing some text content into the file(Steganography). Unfortunately, I couldn't succeed in my attempt. We couldn't retrieve the text content. Possibly it's a huge drawback with this filestream datatype.



create table XMLData(id int identity(1,1),xmlFileName varchar(100),xml_data xml,ownerdata int,updaterdata int)



select * from XMLData
 
GO

DECLARE @xmlFileName VARCHAR(300)
SELECT @xmlFileName = 'D:\Privacy1.xml'
EXEC('
INSERT INTO XMLData(xmlFileName, xml_data)
SELECT ''' + @xmlFileName + ''', xmlData
FROM(
SELECT *
FROM OPENROWSET (BULK ''' + @xmlFileName + ''' , SINGLE_BLOB) AS XMLDATA
) AS FileImport (XMLDATA)
')
GO


SELECT * FROM XMLData
 
Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech

convert varchar to xml in sql server

Here is a small code snippet to convert you varchar data to XML data

declare @data varchar(100) set @data ='



select convert(xml,@data)
 
 
The data will be converted into XML.
 
Cheers,
Venkatesan Prabu .J

27.2.12

A chart element with the name already exists in the 'SeriesCollection'.

While working with Charting control in Windows forms. I found an issue in binding and rebinding the data into the chart control.

Here is the small piece of code to plot the data in a chart

string[] seriesArray = { "Semester1", "Semester2", "Semester3" };



int[] pointsArray = { Convert.ToInt32(0), Convert.ToInt32(semester[1]), Convert.ToInt32(semester[2]) };




this.chart1.Palette = ChartColorPalette.Berry;



this.chart1.Titles.Add("Growth of the Student");



for (int x = 0; x < seriesArray.Length; x++)


{




Series series = this.chart1.Series.Add(seriesArray[x]);


series.Points.Add(pointsArray[x]);


}
 
 
While loading the data for the second time, i got an error "A chart element with the name already exists in the 'SeriesCollection'." The reason is, the chart is already having the series related data bound to it.
 
Solution:
 
chart1.Series.Clear();



chart2.Series.Clear();


chart3.Series.Clear();


this.chart1.Titles.Clear();


this.chart2.Titles.Clear();


this.chart3.Titles.Clear();
 
Cheers,
Venkatesan prabu .J
Head, KaaShiv InfoTech

Issue with Restore database in sql server

While restoring the database I got a peculiar issue and started googling for the same. Got a link from Microsof BOL about this issue.







Reason for this issue:  You are trying to restore the database on the existing database.

SQL Server is thinking that the new restore database is a tail database for the existing database available in the system . Due to this, it's trying to check for the tail end.

Solution : We need to delete the existing one and add the new one
               or else Goto the options page of the restore window and you need to select the  option “overwrite the existing database (With replace )

Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech

26.2.12

Grab Datatables column Name in c#

Here is the code to grab the column name from the datatable and push it or recreate the same columns in another datatable.

foreach(DataColumn dc in objDatatable .Columns )
{

 dtNew.Columns.Add(dc.ColumnName;
}
 
 
Cheers,
Venkatesan Prabu .J
Head, kaaShiv InfoTech

SSAS error


Sometimes, you may get an error "The attribute key cannot be found when processing:"  in  SSAS.

Yesterday, am able to deploy the cube in the SSAS server. Banggg, it's not working now.

Reason for this issue : Mostly, the issue revolves around the duplication of data in to your table.

Step 1: Check for the duplication of data (Remove if it's available)
Step 2:  Reproces the cube and deploy it in the server.

For additional reasons, you can check this URL (http://toddmcdermid.blogspot.in/2009/01/ssas-quick-reference-attribute-key.html)

Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech

25.2.12

MsiGetProductInfo failed to retrieve ProductVersion for package with Product Code - SQL Server installation error


Got an issue while SQL Server installation. below content save me


Solving MsiGetProductInfo failed to retrieve ProductVersion for package with Product Code = ‘{8BDD006D-D5F0-4AAA-BA13-65995063EC44}’. Error code: 1608


SQL Server Setup has encountered the following error:

MsiGetProductInfo failed to retrieve ProductVersion for package with Product Code =
'{0826F9E4-787E-481D-83E0-BC6A57B056D5}'. Error code: 1605..
-------------------------------
********************************************************

From Detail_ComponentUpdate.txt -********************************************************2009-03-16 22:00:59 Slp: Inner exceptions are being indented
2009-03-16 22:00:59 Slp:
2009-03-16 22:00:59 Slp: Exception type: System.InvalidOperationException


2009-03-16 22:00:59 Slp: Message:
2009-03-16 22:00:59 Slp: MsiGetProductInfo failed to retrieve ProductVersion for package with Product Code = '{0826F9E4-787E-481D-83E0-BC6A57B056D5}'. Error code: 1608.
2009-03-16 22:00:59 Slp: Stack:
2009-03-16 22:00:59 Slp: at Microsoft.SqlServer.Configuration.MsiExtension.SetFeatureInstallStateAction.FillInstallPropertyByProductCode(PackageInstallProperty pkg, String prodCode)
2009-03-16 22:00:59 Slp: at Microsoft.SqlServer.Configuration.MsiExtension.SetFeatureInstallStateAction.FillInstallProperty(PackageInstallProperty pkg)
2009-03-16 22:00:59 Slp: at Microsoft.SqlServer.Configuration.MsiExtension.SetFeatureInstallStateAction.ExecuteAction(String actionId)
2009-03-16 22:00:59 Slp: at Microsoft.SqlServer.Chainer.Infrastructure.Action.Execute(String actionId, TextWriter errorStream)


2009-03-16 22:00:59 Slp: at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionInvocation.InvokeAction(WorkflowObject metabase, TextWriter statusStream)
2009-03-16 22:00:59 Slp: at Microsoft.SqlServer.Setup.Chainer.Workflow.PendingActions.InvokeActions(WorkflowObject metaDb, TextWriter loggingStream)


********************************************************


Solution / Fix / Workaround



The above remark line show us the product code related with the error. First, is necessary to know that SQL Server 2008 has around of 30 products registered on the Registry. Each product has a Product code and an installation code as well (GUID).

 this case the Product Code is the following:

{8BDD006D-7863-4D25-9806-08527E285EA4}



The Installation Code is build with the product code in reverse form:


D600DD8368752D460894AE582E72580


One time that you got the Installation Code look into the Windows Registry and delete all the entries found.


Then try again the installation and the result must to be SUCCESSFULLY.
This article is taken from http://sqlpost.blogspot.in/2009/07/sql-server-sql-error-msigetproductinfo.html
Cheers,
Venkatesan Prabu .J

Replace command in SQL Server


Here is an update query to update the email address in Dimcustomer table.

update [dbo].[DimCustomer]



set EmailAddress = REPLACE( EmailAddress,'adventure-works.com','gmail.com')
 
Replace command  is used to replace a particular substring a column. The syntax is Replace(column Name, Old String, New String)
 
Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech

Import Excel data using c#

Upload Excel file data into C#:

   While searching for a functionality of importing excel to database using C#. I searched a lot and couldn't get an appropriate article for a very simple functionality. After 15 minutes of searching, I got some code with bugs in it. Rectified the same and it's for you.


   Below is the code for importing excel data cell by cell. Enjoy coding

Excel.Application xlApp;
private void LeakageChecks_Load(object sender, EventArgs e){
Excel.Workbook xlWorkBook;

Excel.Worksheet xlWorkSheet;

Excel.Range range;

string str;

int rCnt = 0;
int cCnt = 0;

xlApp = new Excel.Application();

xlWorkBook = xlApp.Workbooks.Open(@"C:\LeakData\LeakedData.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);


xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

range = xlWorkSheet.UsedRange;

for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)

{

for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)

{

str = Convert.ToString((range.Cells[rCnt, cCnt] as Excel.Range).Value2);

MessageBox.Show(str);

}

}



xlWorkBook.Close(true, null, null);

xlApp.Quit();

releaseObject(xlWorkSheet);

releaseObject(xlWorkBook);

releaseObject(xlApp);

}



private void releaseObject(object obj)

{

try

{

System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;

}


catch (Exception ex)

{

obj = null;

MessageBox.Show("Unable to release the Object " + ex.ToString());
}


finally

{

GC.Collect();

}

}


Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech

Cannot convert between unicode and non-unicode string data types

While trying to push the data from Flat file to SQL Server I got the error,

" Cannot convert between unicode and non-unicode string data types "  - ->

Solution 1 :- The issue is due to mismatch of the source column and the destination column. We can use derived column/DataConversion tools to map to appropriate data type.

Solution 2 :- For time being, I've changed the destination table columns from unicode(nvarchar) to varchar. Since, it doesn't have any impact on my system.

I am happy with solution 2.

Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech

19.2.12

Unique Identifier in SQL Server

While working with Filestream datatype, I've addressed an issue with Unique Identifier column. Thought of sharing this with you all.

       File stream is a new datatype introduced in SQL Server 2008 to leverage the functionality of storing  the data into the database.

       Below is the syntax to create a table in the database,
 
CREATE TABLE [dbo].[DOC_details2](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [F_Data] [varbinary](max) FILESTREAM  NOT NULL,
    [F_Name] [nvarchar](1000) NULL,
    [F_Date] [datetime] NULL,
    [RowGuid] [uniqueidentifier] ROWGUIDCOL  NOT NULL
)

        While creating the filestream storage table, we need to specify one column as uniqueidentifier and it's a mandatory functionality.

         My question now is, How can we insert the data in a unique identifier column?

Solution 1:   We need to use newid() in SQL Server to generate the GUID

ALTER TABLE [dbo].[DOC_details2] ADD  CONSTRAINT [DF_DOC_details2_RowGuid]  DEFAULT (newid()) FOR [RowGuid]
GO


Solution 2: From C#, we can make it out the method System.Guid.NewGuid.

Cheers,
Venkatesan Prabu .J

8.2.12

XSD in SQL Server

XML validation using XSD in SQL Server:
 
  To acheive the validation process, we will be utilising the option of Regex pattern.

Here is the list of steps to be done in XSD implementation on the XML.

1. Check for the existing XML Schema collection -> Drop it.
2. Create XSD and bind it with XML Schema Collection
3. Create XML of type XML Schema Collection
4. If it binds, it indicates the XML is satisfying the condition specified by the XSD.


Regex pattern, I've provided is "The username and password can contain any number of special characters and any number of integers but it should not contain the special character - and /  in it.

Let's move on to the querying part.




IF EXISTS(



SELECT * FROM sys.xml_schema_collections


WHERE name = 'StringPattern'


) BEGIN


DROP XML SCHEMA COLLECTION ValidationPattern


END


GO


-------------------------------------------------------------


create XML SCHEMA COLLECTION ValidationPattern AS '


'
















































-------------------------------------------------------------






GO


DECLARE @x XML(StringPattern)


SET @x = 'AC78HJGVHJ35AC78HJGVHJ35'


SELECT @x
-- This will give the output
-----------------------------------------------
DECLARE @x XML(StringPattern)


SET @x = 'AC78HJGVH/J35AC78HJGVHJ35'

SELECT @x
------This won't give the output
--------------------------------------------------


Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech

3.2.12

Microsoft.AnalysisServices.AdomdClient issue


References for using Microsoft.AnalysisServices and Microsoft.AnalysisServices.AdomdClient

I got the information from Microsoft site which may be useful to you.
    Download the appropriate file by clicking one of the links below, then run the downloaded file to install thSat package. Each package indicates the audience(s) for which it was intended, as follows:
      Customer: An individual may want to install this for additional licensed functionality such as interoperability. Partner: An ISV may want to ship this as a redistributable component as part of their application. Developer: A programmer may want to install this to support application development.
    Note: To archive a copy of the license terms, prior to accepting them, copy and paste the terms to a word processing program, then print or save the file to your favorite directory. Microsoft ADOMD.NET
      ADOMD.NET is a Microsoft .NET Framework object model that enables software developers to create client-side applications that browse metadata and query data stored in Microsoft SQL Server 2008 Analysis Services. ADOMD.NET is a Microsoft ADO.NET provider with enhancements for online analytical processing (OLAP) and data mining. Note:The English ADOMD.NET setup package installs support for all SQL Server 2008 languages. Audience(s): Customer, Partner, Developer Microsoft Analysis Management Objects
        Analysis Management Objects (AMO) is a .NET Framework object model that enables software developers to create client-side applications to manage and administer Analysis Services objects. Audience(s): Customer, Partner, Developer
      Microsoft SQL Server 2008 Analysis Services 10.0 OLE DB Provider
        The Analysis Services 10.0 OLE DB Provider is a COM component that software developers can use to create client-side applications that browse metadata and query data stored in Microsoft SQL Server 2008 Analysis Services. This provider implements both the OLE DB specification and the specification’s extensions for online analytical processing (OLAP) and data mining. Note: Microsoft SQL Server 2008 Analysis Services 10.0 OLE DB Provider requires Microsoft Core XML Services (MSXML) 6.0, also available on this page. Audience(s): Customer, Partner, Developer
            Download and Install the above softwares. Got to your Dotnet project, Add reference browse and you can identify the dll in the path C:\Program Files\Microsoft.NET\ADOMD.NET\100. Add it and you problem is resolved.
    • Cheers,
    • Venkatesan Prabu .J

    1.2.12

    Fetch a pattern of data in SQL Server

    Fetch a pattern of data:

          Consider, If you want to fetch a specific pattern of data like I want to fetch customerkey which are able to divide by 100. A pattern of divide of 100 values.
    In that case, the query created is as below.

    SELECT TOP 1000 [CustomerKey]

    ,[GeographyKey]
    ,[CustomerAlternateKey]
    ,[Phone]
    ,[DateFirstPurchase]
    ,[CommuteDistance]
    FROM [dbo].[DimCustomer]
    where (CustomerKey % 100 =0)

    Cheers,
    Venkatesan Prabu .J
    www.kaashivinfotech.com

    My T-SQL Gallery @code.msdn.microsoft


    Created my own T-SQL Gallery in Microsoft site. Do visit the same and share your feedback,

    http://code.msdn.microsoft.com/VenkatSQLSample/Thread/List.aspx

    Thanks and Regards,
    Venkatesan Prabu .J

    SQL Server Interview questions - Part 1

    What is the significance of NULL value and why should we avoid permitting null values?
    Null means no entry has been made. It implies that the value is either unknown or undefined.We should avoid permitting null values because Column with NULL values can't have PRIMARY KEY constraints. Certain calculations can be inaccurate if NULL columns are involved.

    What is SQL whats its uses and its component ?
    The Structured Query Language (SQL) is foundation for all relational database systems. Most of the large-scale databases use the SQL to define all user and administrator interactions. It enable us to retrieve the data from based on our exact requirement. We will be given a flexibility to store the data in our own format.


    The DML component of SQL comprises four basic statements:
    * SELECT to get rows from tables
    * UPDATE to update the rows of tables
    * DELETE to remove rows from tables
    * INSERT to add new rows to tables


    What is DTS in SQL Server ?
    Data Transformation Services is used to transfer the data from one source to our required destination. Considering am having some data in sql server and I need to transfer the data to Excel destination. Its highly possible with dialogue based tool called Data Transformation services. More customization can be achieved using SSIS. A specialized tool used to do such migration works.


    What is the difference between SQL and Pl/Sql ?

    Straight forward. SQL is a single statement to finish up our work.Considering, I need some data from a particular table. “Select * from table” will fetch the necessary information. Where as I need to do some row by row processing. In that case, we need to go for Procedural Logic / SQL.

    What is the significance of NULL value and why should we avoid permitting null values?
    Null means no entry has been made. It implies that the value is either unknown or undefined.We should avoid permitting null values because Column with NULL values can't have PRIMARY KEY constraints. Certain calculations can be inaccurate if NULL columns are involved.

    Difference between primary key and Unique key?
    Both constraints will share a common property called uniqueness. The data in the column should be unique. The basic difference is,
    · Primary key won’t allow null value. Whereas, unique key will accept null value but only one null value.
    · On creating primary key, it will automatically format the data inturn creates clustered index on the table. Whereas, this characteristics is not associated with unique key.
    · Only one primary key can be created for the table. Any number of Unique key can be created for the table.

    Select Statement in SQL Server

    Select Statement in SQL Server

    String Functions in sql server

    String Functions in sql server
    Substring/Len/replace/Ltrim/Rtrim

    SQL Server Interview Question - Part 2

    What is normalization?

    Normalization is the basic concept used in designing a database. Its nothing but, an advise given to the database to have minimal repetition of data, highly structured, highly secured, easy to retrieve. In high level definition, the Process of organizing data into tables is referred to as normalization.


    What is a stored procedure:
    Stored procedures are precompiled T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements. As, its precompiled statement, execution of Stored procedure is compatatively high when compared to an ordinary T-SQL statement.


    What is the difference between UNION ALL Statement and UNION ?
    The main difference between UNION ALL statement and UNION is UNION All statement is much faster than UNION,the reason behind this is that because UNION ALL statement does not look for duplicate rows, but on the other hand UNION statement does look for duplicate rows, whether or not they exist.

    Example for Stored Procedure?
    They are three kinds of stored procedures,1.System stored procedure – Start with sp_2. User defined stored procedure – SP created by the user.3. Extended stored procedure – SP used to invoke a process in the external systems.Example for system stored proceduresp_helpdb - Database and its propertiessp_who2 – Gives details about the current user connected to your system. sp_renamedb – Enable you to rename your database


    What is a trigger?

    Triggers are precompiled statements similar to Stored Procedure. It will automatically invoke for a particular operation. Triggers are basically used to implement business rules.


    What is a view?
    If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specfic users to see only specific columns based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time.


    What is an Index?
    When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index.


    What are the types of indexes available with SQL Server?

    There are basically two types of indexes that we use with the SQL ServerClustered -

    1. It will format the entire table, inturn physically sort the table.

    2. Only one clustered index can be created for a table.

    3. Data will be located in the leaf level.

    4. By default, primary key will create clustered index on the table.

    Non-Clustered Index

    1. It wont touch the structure of the table.

    2. It forms an index table as reference to the exact data.

    3. A reference to the data will be located in the leaf level.

    4. For a table, we can create 249 non clustered index.

    Happy Learning!!!
    Regards,
    Venkatesan Prabu .J

    SQL Interview question

    Extent Vs Page?

    Pages are low level unit to store the exact data in sql server. Basically, the data will be stored in the mdf, ldf, ndf files. Inturn, pages are logical units available in sql server.The size of the page is 8KB.

    Eight consecutive pages will form an extent 8 * 8KB = 64KB.

    Thus I/O level operation will be happening at pages level.The pages will hold a template information at the start of each page (header of the page).

    They are,

    1. page number,

    2. page type,

    3. the amount of free space on the page,

    4. the allocation unit ID of the object that owns the page.

    Extents will be classifed into two types,

    1. Uniform extents

    2. Mixed extents

    Uniform Extents:It occupied or used by a single object. Inturn, a single object will hold the entire 8 pages.Mixed

    Extents:Mulitple objects will use the same extent. SQL Server will allow a max of eight objects to use a shared extent.

    Property of SQL Server :Initally if an object is created, sql server will allocate the object to the mixed extent and once if the size reaches 8 pages and more... immediately, a new uniform extent will be provided for that particular object.

    Herecomes, our fragmentation and reindexing concepts.

    Best Joke - Enjoy it

    Best Joke - Enjoy it