Hot News!

Not Available

Click Like or share to support us!

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

Sep 14, 2015

Advanced Sql Selecting Rows With Max Value From Groups

SQL is never hard but definitely tedious. You know what I mean.
Occasionally I tend to create a relatively complicated query instead of fetching the data back and do the processing in my code. Sometimes for the performance, and sometimes just because I like challenges.
I know, I never am a SQL expert. But anyway, it might help.
Say we have a table like the following:
DepartmentEmployeeSalary
AJohn1000
AMichael1200
ABob880
BTed2000
BJane2000
CAlly2000
CKent4000
And we want to get a query of all employees having the highest pay from each department. What SQL query should we have?
Well, first we need to find what the highest pay of each department is:
SELECT 
  DEP.DEPARTMENT, MAX(DEP.SALARY) 
FROM 
  DEPARTMENT DEP 
GROUP BY 
  DEP.DEPARTMENT
This will give you a list of department with its highest pay. But we do want to fetch the complete row so that we could know who that employee is. So how do we proceed from here?
We need sub query and EXISTS predicate:
SELECT * 
FROM 
  DEPARTMENT 
WHERE 
  EXISTS (
    SELECT 
      DEP.DEPARTMENT 
    FROM 
      DEPARTMENT DEP 
    GROUP BY 
      DEP.DEPARTMENT 
    HAVING 
      DEPARTMENT.DEPARTMENT = DEP.DEPARTMENT AND 
      DEPARTMENT.SALARY = MAX(DEP.SALARY)
  )
The result looks like this:
DepartmentEmployeeSalary
AMichael1200
BTed2000
BJane2000
CKent4000
The speed of this query doesn’t seem very bad. In fact, it performs far better than I originally thought since it involves sub query.

source:https://bryantsai.com/advanced-sql-selecting-rows-with-max-value-from-groups/

Aug 27, 2015

MS SQL Server with Khmer Unicode

MS SQL Server is a product of Microsoft that we use it for store data, information and we can easy find that data when you need. MS SQL Server is the database application for manage data or any information of organization. If we compare with MS Access we can say MS SQL Server is better because MS SQL Server have more features, tools, function than MS Access in manage data.  Today I have one topic to share you about how to make MS SQL Server support with Khmer Unicode.
This is the topic that shows you about how to insert, update, delete data in Khmer to table and how to search data as Khmer language. It is the nice topic that can help who that starting build application with Khmer Unicode

1. How can we insert Khmer Unicode to table?
You need to configure something when you create table. If you want your table support with Khmer Unicode please choose datatype is nvarchar and in collation properties Khmer_100. Please create tblStudents(ID,Name,Sex) and set datatype below:


In field Name properties please set Collation to Khmer_100


2. After you create table you need to know the query that can input Khmer Unicode to table also.

             insert into tblStudents(ID,Name,Sex)
             values('1',N'សុវណ្ណ','M')

“N” character is the special string that allow input Khmer Unicode to field of table. Please run this script and see the result in table.


       3. How to Search with Khmer Unicode

           We need still use “N” when we search data in tblStudents. Please see example below:

       Select * from tblStudents
       where Name='សុវណ្ណ'

          if we write this select we will now have data.


            Then try to change to this scripts

      Select * from tblStudents
      where Name=N'សុវណ្ណ'

              Result:


You also can use “Like” to select with Khmer Unicode too.


This topic is very useful to help you to build application by using Khmer Unicode. And I hope it can help you to build application. If you have any issue please command I will to support you.

(source: http://kh-code.blogspot.com)

Jul 2, 2012

C#: Storing and Retrieving Images from SQL Server Using Strored Procedures

Introduction

First of all I have to tell you I am not a Expert but I will try by best to explain the solution. In this article I am going to explain how to store and retrieve image from SQL server database by using C# as the front end programming language and Stored Procedures as the back end language for SQL server. Reason to write article about this topic is give proper understanding for the beginners.

Prerequisites

You need basic knowledge about Stored Procedures and C# language.

Tools Used

  • SQL Server 2008
  • Visual Studio 2010
  • C# (Windows Form Application)

Preparing the Development Environment

SQL Server Environment

Creating Tables
In this example I am going to use only one table call ImageData and it only contain two fields call ImageID and other one is call ImageData, data types of this fields are int and image. Use below SQL script to create table.
 CREATE TABLE [dbo].[ImageData]
 (
    [ImageID] [int] IDENTITY(1,1) NOT NULL,
    [ImageData] [image] NULL,
 CONSTRAINT [PK_ImageData] PRIMARY KEY CLUSTERED 
 (
    [ImageID] ASC
 )
 WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, 
 ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
 ) 
 ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  
Creating Stored Procedures
In this example I am going to use Four(4) Stored Procedures call ReadAllImage, ReadAllImageIDs, ReadImage, SaveImage and use below SQL scripts to create those Procedures.
CREATE proc [dbo].[ReadAllImage] as 
SELECT * FROM ImageData 
GO
CREATE proc [dbo].[ReadAllImageIDs] as 
SELECT ImageID FROM ImageData 
GO
CREATE proc [dbo].[ReadImage] @imgId int as 
SELECT ImageData FROM ImageData 
WHERE ImageID=@imgId 
GO 
CREATE proc [dbo].[SaveImage] @img image as
INSERT INTO ImageData(ImageData)
VALUES (@img)
GO

Visual Studio Environment

Creating Windows Form
In this exapmle I am going to use only one Form and set basic properties according to the below table.

Control Name
Property Name
Property Value
Form
Name
UsingSPs
Text
Storing and Retrieving Images from SQL Server using C#.NET
Button1
Name
btnLoadAndSave
Text
<<--Load and Save Image-->>
Button2
Name
btnRefresh
Text
Refresh
Button3
Name
btnDisplayImage
Text
Display Image
ComboBox
Name
cmbImageID
GroupBox
Name
grbPicBox
Text
Image Display
Anchor
Top, Bottom, Left, Right
PictureBox
Name
picImage
Dock
Fill

Start Cording

Now we have all the things to start our cording and this is the part we have to get better concentrate of our development. Anyway I will try my best to explain the cording, then let's start our journey.
In this example I am going to use one more class call DBHandler other than the From, purpose of this class is to handle the database connection details. Here is the code for that class.

Handling Database Connection String

public class DBHandler
{        
  public static string SrvName = @"DBSERVER"; //Your SQL Server Name
  public static string DbName = @"DB";//Your Database Name
  public static string UsrName = "us";//Your SQL Server User Name
  public static string Pasword = "xxxx";//Your SQL Server Password
        
  /// <summary>
  /// Public static method to access connection string throw out the project 
  /// </summary>
  /// <returns>return database connection string</returns>
  public static string GetConnectionString()
  {
     return "Data Source=" + SrvName + "; initial catalog=" + DbName + "; user id=" 
     + UsrName + "; password=" + Pasword + ";";//Build Connection String and Return
  }
}

Select and Store Image to Database

Before Start the Coding add below namespaces to your code.
using System.IO;
using System.Data;
using System.Data.SqlClient;
Here I am going to explain the btnLoadAndSave button click event process step by step.
  1. Create Connection to the Database.
  2. Create object call fop of type OpenFileDialog.
  3. Set InitialDirectory Property of the object fop.
  4. Set Filter Property of the object fop(in here user can select only .jpg files)
  5. Display open file dialog to user and only user select a image enter to if block.
  6. Create a file stream object call FS associate to user selected file.
  7. Create a byte array with size of user selected file stream length.
  8. Read user selected file stream in to byte array.
  9. Check whether connection to database is close or not.
  10. If connection is close then only open the connection.
  11. Create a SQL command object call cmd by passing name of the stored procedure and database connection.
  12. Set CommandType Property of the object cmd to stored procedure type.
  13. Add parameter to the cmd object and set value to that parameter.
  14. Execute SQL command by calling the ExecuteNonQuery() method of the object cmd.
  15. Call user defined method to load image IDs to combo box. (this method will explain later so don't worry now)
  16. Display save successful message to user.
  17. Catch if any error occur during the above code executing process.
  18. Finally Check whether connection to database is open or not, if connection is open then only close the connection.
Below Demonstrate the Complete Select and Store image to database code.
SqlConnection con = new SqlConnection(DBHandler.GetConnectionString());
try
 {
   OpenFileDialog fop = new OpenFileDialog();
   fop.InitialDirectory = @"C:\"; 
   fop.Filter = "[JPG,JPEG]|*.jpg";
   if (fop.ShowDialog() == DialogResult.OK)
   {
     FileStream FS = new FileStream(@fop.FileName, FileMode.Open, FileAccess.Read);
     byte[] img = new byte[FS.Length];
     FS.Read(img, 0, Convert.ToInt32(FS.Length));

     if (con.State == ConnectionState.Closed)
       con.Open();
     SqlCommand cmd = new SqlCommand("SaveImage", con);
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.Parameters.Add("@img", SqlDbType.Image).Value = img;
     cmd.ExecuteNonQuery();
     loadImageIDs();
     MessageBox.Show("Image Save Successfully!!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
   }
   else
   {
     MessageBox.Show("Please Select a Image to save!!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
   }

 }
 catch (Exception ex)
 {
   MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
 }
 finally
 {
   if (con.State == ConnectionState.Open)
     con.Close();
 }

Retrieving and Display Image

Here I am going to explain the btnDisplayImage button click event process step by step.
  1. Check whether user select image ID or not from combobox.
  2. Check whether picture box contain image or not.
  3. Clear the image of the picture box if there is image.
  4. Create Connection to the Database.
  5. Create a SQL command object call cmd by passing name of the stored procedure and database connection.
  6. Set CommandType Property of the object cmd to stored procedure type.
  7. Add parameter to the cmd object and set value to that parameter.
  8. Create SQL data adapter object call adp by passing previously created cmd object.
  9. Create a data table object call dt to hold result of the cmd object.
  10. Check whether connection to database is close or not.
  11. If connection is close then only open the connection.
  12. Object dt fill with data by calling the fill method of adp objec.
  13. Check whether object dt contain any data row or not.
  14. Ccreate memory stream object call ms by passing byte array of the image.
  15. Set image property of the picture box by creating a image from memory stream.
  16. Set SizeMode property of the picture box to stretch.
  17. Call refresh metod of picture box.
  18. Catch if any error occur during the above code executing process.
  19. Finally Check whether connection to database is open or not, if connection is open then only close the connection.
Below Demonstrate the Complete Retrieving and Display Image code.
if (cmbImageID.SelectedValue != null)
{
    if (picImage.Image != null)
        picImage.Image.Dispose();

    SqlConnection con = new SqlConnection(DBHandler.GetConnectionString());
    SqlCommand cmd = new SqlCommand("ReadImage", con);
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.Parameters.Add("@imgId", SqlDbType.Int).Value = 
              Convert.ToInt32(cmbImageID.SelectedValue.ToString());
    SqlDataAdapter adp = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    try
    {
        if (con.State == ConnectionState.Closed)
            con.Open();
        adp.Fill(dt);
        if (dt.Rows.Count > 0)
        {
            MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["ImageData"]);
            picImage.Image = Image.FromStream(ms);
            picImage.SizeMode = PictureBoxSizeMode.StretchImage;
            picImage.Refresh();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", 
              MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        if (con.State == ConnectionState.Open)
            con.Close();
    }
}
else
{
    MessageBox.Show("Please Select a Image ID to Display!!", 
       "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Jun 12, 2012

Tip: Importing Data from MS Access 2010 64-bit .accdb database into SQL Server using SSIS

Problem:
You can’t connect using Native OLEDB \Microsoft Jet 4.0 OLEDB Provider.  It fails with following error message:
Test connection failed because of an error in initializing provider. Unrecognized database format 'C:\Users\vishah\Documents\myDB.accdb'.

Solution:

image

Tip: Importing Microsoft Access 2007 Database Tables into SQL Server

Microsoft SQL Server 2005 and 2008 offer the Import and Export Wizard to move data to and from an external source. You can also create a basic SQL Server Integration Services (SSIS) package which can be used later in the Business Intelligence Development Project.
With the Import and Export wizard, you can access different types of data sources. These sources include database formats such as Microsoft Access, Microsoft SQL Server, flat files, Microsoft Excel, and Oracle. This article discusses importing Access 2007 database tables into MS SQL Server 2005/2008.
Importing Microsoft Access MDB databases (2003-format or earlier) is a built in feature of SQL Server. However, because of the difference between the database engine of Microsoft Access 2007 and earlier versions, it is not possible to connect to the Access 2007 database (*.ACCDB) using the built-in data source “Microsoft Access”. To import data from a Microsoft Access 2007 database, you must install the OLEDB Provider for Microsoft Office 12.0 Access Database Engine. Refer to the following FMS tip for details:
After installing this driver, open SQL Server Management Studio and connect to the desired instance of SQL Server database engine. In the Object Explorer, it shows database list available in that instance of SQL Server. Select a desired database or create a new one. Right Click this database and select Tasks -> Import Data.

Now follow the several pages of the wizard. The steps below detail how to import data into a SQL Server 2005 database, but the steps are very similar in SQL Server 2008.
On the first page, select the Data source from which you want to import the data. There are several data sources also available such as:
  • Microsoft OLEDB provider for SQL Server
  • Microsoft OLEDB provider for Oracle
  • SQL Native Client
  • Microsoft Access
  • Microsoft Excel, etc…
Because of the difference between the database engine of Microsoft Access 2007 and earlier version of Microsoft Access, it is not possible to connect to the Access 2007 database using data source “Microsoft Access”. You can use this if you wish to import data from a MDB format, but not an ACCDB from Access 2007.
If you have properly installed the 2007 Office System driver, you will see another Data Source option: “Microsoft Office 12.0 Access Database Engine.”


Apr 30, 2012

How to Install SQL server 2008 on Windows 7


First you need the installer, download it from here.
Requirements:
Visual Studio 2010 or VS 2008 SP1
Step 1: Double click on the installer. It will take some time to extract. After that an window  will open as follow.
First window of installation
Step 1
Step 2: From this window click on the Installation menu (See Left). Now there will be appear some option under Installation. From right, click on the option New SQL Server stand-alone installation or add features to an existing installation.
Note: After Clicking on that a window may appear as bellow. Just click on the button Run Program of that.
Click Run Program
Note
Step 3: Now setup will take a moment to complete some operation. To continue there can not be any operation with status failed. If any operation fails then it will not be possible to continue installation. Click OK
Every operation should be passed
Step 4