Wednesday, December 30, 2009

Joins in sql server 2005


Joins in sql server 2005
What is Join?
A join is used to combine columns from two or more tables into a single result set. To join data from two tables you write the names of two tables in the FROM clause along with JOIN keyword and an ON phrase that specifies the join condition. The join condition indicates how two tables should be compared. In most cases they are compares on the base on the relationship of primary key of the first table and foreign key of the second table.I will tell you about the following types of joins in that article.
Join Types
You can do two types of Join: ‘Inner’ Join or an ‘Outer’ Join.
Inner Join:

This will only return rows when there is at least one row in both tables that match the join condition.
Syntax:
SELECT * FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name = table_name2.column_name
Example Inner Join Statement
SELECT * FROM Individual
INNER JOIN Publisher
ON Individual.IndividualId = Publisher.IndividualId

Note: We could use table aliases instead of the full table name. This will keep our statement shorter. For example:
SELECT * FROM Individual AS Ind
INNER JOIN Publisher AS Pub
ON Ind.IndividualId = Pub.IndividualId

Outer Join:
  • LEFT OUTER JOIN (or LEFT JOIN): This will return rows that have data in the left table (left of the JOIN keyword), even if there's no matching rows in the right table.
  • RIGHT OUTER JOIN (or RIGHT JOIN): This will return rows that have data in the right table (right of the JOIN keyword), even if there's no matching rows in the left table.
  • FULL OUTER JOIN (or FULL JOIN): This will return all rows, as long as there's matching data in one of the tables.
Syntax:
Left Join:
SELECT * FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name = table_name2.column_name

Right Join:
SELECT * FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name = table_name2.column_name

Full Join:
SELECT * FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name = table_name2.column_name

Left Outer Join

Use this when you only want to return rows that have matching data in the left table, even if there's no matching rows in the right table.

Example SQL statement

SELECT * FROM Individual AS Ind
LEFT JOIN Publisher AS Pub
ON Ind.IndividualId = Pub.IndividualId
 

Source Tables

Left Table
Id
FirstName
UserName
1
Bharat
bharat
2
Rahul
Rahul
3
Piyush
Piyush
4
Sandy
sandy
Right Table
IndividualId
AccessLevel
1
Programmer
2
Tester
3
Sales Executive
10
Manager

Result

IndividualId
FirstName
UserName
IndividualId
AccessLevel
1
Bharat
Bharat
1
Programmer
2
Rahul
Rahul
2
tester
3
Piyush
Piyush
3
SalesExecutive
4
Sandy
sandy
Null
null

Right Outer Join

Use this when you only want to return rows that have matching data in the right table, even if there's no matching rows in the left table.

Example SQL statement

SELECT * FROM Individual AS Ind
RIGHT JOIN Publisher AS Pub
ON Ind.IndividualId = Pub.IndividualId
 

Source Tables

Left Table
Id
FirstName
UserName
1
Bharat
bharat
2
Rahul
Rahul
3
Piyush
Piyush
4
Sandy
sandy
Right Table
IndividualId
AccessLevel
1
Programmer
2
Tester
3
Sales Executive
10
Manager

Result

IndividualId
FirstName
UserName
IndividualId
AccessLevel
1
Bharat
Bharat
1
Programmer
2
Rahul
Rahul
2
tester
3
Piyush
Piyush
3
SalesExecutive
Null
Null
null
10
Manager

Full Outer Join

Use this when you want to all rows, even if there's no matching rows in the right table.

Example SQL statement

SELECT * FROM Individual AS Ind
FULL JOIN Publisher AS Pub
ON Ind.IndividualId = Pub.IndividualId
 

Source Tables

Left Table
Id
FirstName
UserName
1
Bharat
bharat
2
Rahul
Rahul
3
Piyush
Piyush
4
Sandy
sandy
Right Table
IndividualId
AccessLevel
1
Programmer
2
Tester
3
Sales Executive
10
Manager

Result

IndividualId
FirstName
UserName
IndividualId
AccessLevel
1
Bharat
Bharat
1
Programmer
2
Rahul
Rahul
2
tester
3
Piyush
Piyush
3
SalesExecutive
4
Sandy
Sandy
Null
Null
Null
Null
null
10
Manager

 

Tuesday, December 22, 2009

How to debug a Stored Procedure in visual studio

There are two way to debug a stored procedure in visual studio.

I am going to discuss both one by one.
##############    1st method    ######################

open server explorer in visual studio.

open / add new connection to database.

drill down untill u find your store procedure.

right click on your procedure and then click Step Into Stored Procedure.

The Run stored procedure dialog box opens, which lists the parameters of the stored procedure if required. provide the input parameter if required and click OK
 

a window opens that displays the text of the stored procedure. 

The first executable line of the stored procedure is highlighted. Press F11 to step through the stored procedure to completion.
 
In the Output window, the following message is displayed, which indicates successful execution: 
 The program ‘SQL Debugger: T-SQL’ has exited with code 0 (0×0).
################    end 1st Method   ########################

################    2nd method    ###########################

create your application and write your desired code.

set a breakpoint in the code where you calls the store procedure.
like at
SqlDataReader dr = cmd.ExecuteReader();
line

In Solution Explorer, right-click the project (not the solution) and open the Property pages. Click Configuration Properties in the tree and then click to select the SQL Server Debugging check box on the Debugging page to enable stored procedure debugging.

In Server Explorer, locate and open the stored procedure . Right-click the stored procedure and then click Edit Stored Procedure.

set a Breakpoint in the store procedure where you want to debug.


run the application

Press F11. Code execution steps from the ExecuteReader method into the stored procedure window.


Press F11 again and procedure executes line by line as you press F11. Then control returns to your Visual Basic project, and the project runs to completion.

To continue to step through the Visual Basic code after you step out of the stored procedure, you must set a second breakpoint in the Visual Basic code after the call to the stored procedure. For example, you can set the second breakpoint on the following line:While (dr.Read)

##############    end 2nd Method   #####################

Sunday, December 20, 2009

SQL Bulk copy in ADO.NET using C#

Sometimes you need to copy a large numbers of rows from any resources to sql server database. ASP.NET provides a class for that purpose in ADO.NET SqlBulkCopy.

Sometimes we need to copy a table data from one database to a table of another database.
To do so, ADO.NET provides SqlBulkCopy class


we can use this class to copy data from one resource to sql server.

I use following code to satisfy my need.

the namespace used for this

using System.Data.SqlClient;


code to copy bulk data


// code to establish connection to source datasource and fetching the data in DataTable.

        DataTable dtSource = new DataTable();
        string Sourceconstr = @"Data Source=IITCS1;Initial Catalog=Test;Integrated Security=SSPI;";
        SqlConnection Sourcecon = new SqlConnection(Sourceconstr);
        SqlDataAdapter daSource = new SqlDataAdapter("Select * from product", Sourcecon);
        daSource.Fill(dtSource);

 // Initializing an SqlBulkCopy object

string Destconstr="Data Source=IITCS2;Initial Catalog=ProductionTest;Integrated Security=SSPI";
SqlConnection Destcon = new SqlConnection(Destconstr);
SqlBulkCopy oSqlBulkCopy  = new SqlBulkCopy(Destcon);

// Copying data to destination

oSqlBulkCopy.DestinationTableName = "Test1";
oSqlBulkCopy.WriteToServer(dtSource);

// Closing connection and the others

oSqlBulkCopy.Close();

you can provide 
DataRow[] or
DataTable or
SqlDataReader


to the WriteToServer method of SQLBULKCOPY class as input parameter




Hope this code helps to find sort out your problem.

Enjoy coding..............................

Saturday, December 19, 2009

code for sending mail in asp.net using c#

  I write following function in my asp.net application to send E-Mail

namespace used for this


using System.Net.Mail;

function that sends the mail
This function requires receivers mail Id,message body of the mail.

 public bool SendMail(string To, string MessageBody)
    {
        // System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
        // System.Net.Mail.SmtpClient is the alternate class for this in 2.0


        try
        {
            SmtpClient smtpClient = new SmtpClient();
            MailMessage message = new MailMessage();
            string From = "sender mail Id";
            MailAddress fromAddress = new MailAddress(From);


            // You can specify the host name or ipaddress of your server
            // Default in IIS will be localhost 
            smtpClient.Host = "relay-hosting.secureserver.net";


            //Default port will be 25
            smtpClient.Port = 25;


            //From address will be given as a MailAddress Object
            message.From = fromAddress;


            // To address collection of MailAddress
            message.To.Add(To);
            message.Subject = "Welcome to world of fresh flowers and gifts";


            message.CC.Add(new MailAddress("Cc Mail Id"));
            message.Bcc.Add(new MailAddress("another Bcc mail Id"));
            message.Bcc.Add(new MailAddress("Another Bcc mail Id"));
        
            message.IsBodyHtml = false;


            // Message body content
            message.Body = MessageBody;


            // Send SMTP mail
            smtpClient.Send(message);
            return true;
            
        }
        catch
        {
            return false;
        }


    }

hope this code will help you in sending Email from your asp.net Application.

Enjoy Coding..........................

sending mail from gmail in asp.net

I write following function to send mail using my Gmail Id in asp.net.



public bool SendGMail(string pTo, string pSubject, string pBody)
    {
        try
        {
            System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
           
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "smtp.gmail.com");
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", "2");
            //sendusing: cdoSendUsingPort, value 2, for sending the message using     
            //the network.      
            //smtpauthenticate: Specifies the mechanism used when authenticating  
            //to an SMTP    
            //service over the network. Possible values are:   
            //- cdoAnonymous, value 0. Do not authenticate.   
            //- cdoBasic, value 1. Use basic clear-text authentication.   
            //When using this option you have to provide the user name and password 
            //through the sendusername and sendpassword fields.   
            //- cdoNTLM, value 2. The current process security context is used to  
            // authenticate with the service.  
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
            //Use 0 for anonymous      
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "kushwaha.bharat@gmail.com");
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "Password");
            myMail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
            myMail.From = "kushwaha.bharat@gmail.com";
            myMail.To = pTo;
            myMail.Subject = pSubject;
            myMail.Priority = System.Web.Mail.MailPriority.High;
            myMail.BodyFormat = System.Web.Mail.MailFormat.Html;
            myMail.Body = pBody;
            //if (pAttachmentPath.Trim() != "")
            //{
            //    MailAttachment MyAttachment = new MailAttachment(pAttachmentPath);
            //    myMail.Attachments.Add(MyAttachment);
            //    myMail.Priority = System.Web.Mail.MailPriority.High;
            //}
            System.Web.Mail.SmtpMail.SmtpServer = "smtp.gmail.com:465";
            System.Web.Mail.SmtpMail.Send(myMail);
            return true;
        }
        catch (Exception ex)
        { throw; }
    }


Hope this code help you in sending EMAIL from asp.net using your Gmail Id.

Enjoy Coding..............................