Wednesday, August 22, 2012

How to add an mdf file to SQL server 2008.


In this article I will like to tell you how to add the MDF file to SQL server 2008.
First open the “Microsoft SQL Server Management Studio” via Start Menu of Windows.
Please log in to require database.
Open the required database as Shown below
< image >
Right click on “Database” and click “Attach..”
You will see a pop-up window . Then click “ADD” button you will get following
One more Pop-up window Occurs. Browse throght and click on folder which has your required “.mdf” file.
Note : if you have a MDF file , it is better to put that in below folder : C:\Program Files\Microsoft SQL server\MSSQL10_50.databasename\MSSQL\DATA\

After browsing through the folder and finding the require mdf file , select the file and it shows windows as follows


Now click “ADD catalog” button. It will execute and the database (tables and all Db objects) are restored / added back to newly created database.

How to open or connect to local database in SQL server 2008 (after installation)


Many of us have an issue after installation of SQL server 2008 management studio as how to start and connect the local database to check it is working fine. After successful installation of SQL server 2008, we start the SQL server 2008 from start menu of windows and stuck on login screen and attempt to login by windows authentication. But it does not login simply (like it does in SQL server 2005 /SQL express 2005).
Trying with password we used in installation, changing setting in options and many others attempts but still not able login in. Also after trying different server name as “local”,”yourpc-yourname”, we fail to login. Here I will tell you how to login into default database (windows authentication /mixed mode) for SQL server 2008.
It all starts with the installation of SQL server 2008. While installing the software please keep a note of the instance you choose while installation and the password you kept for database
The installation asks for the instance to be used for SQL server 2008 on “Instance configuration” page of Installation as shown below.

 



If you choose “Default instance”, then it will take the “instance id” and “instance root directory” automatically and install the database in default location. But if you choose “Named Instance” then you can assign a name to our database and the path where we can set our Database and also can change the settings below.
The next important thing while installation to note is “Database Engine Configuration” Page as sown below.

 



It has tab as “Account Provisioning” and in that there is option for “Authentication mode”. Authentication mode determines how the database will be accessed/ connected with user/ applications.
If you choose a Windows authentication mode’ here, then you can login to SQL server 2008 always by Windows authentication (admin/owner of the system or server).There is No ID and Password to log in to database via web application as well as SQL server management studio.
This is the easiest way to install and use SQL server 2008 but limitation that your web application needs to be on local system and you cannot access this database in network. This method is useful only when you have a dedicated server where you have full access to your remote server, your SQL database and your web applications.
But in case of shared environments, we have to use “mixed mode” so that we can assign a username and a password to login to our database. By this mode we can access our Database of SQL Server 2008 using ID: sa and Password: “you give here
NOTE:
The password entered here must be noted.
ID: sa
Password: “you_set_here”


The web application as well as SQL server management studio can use this ID and Password with server name (as PC name) and connect to data base. In network you can use this database too by id password and server name as “IP Address” of the installation system. (Note: Some configuration is also needed to be done in SQL server 2008, to make it access via network. I will post that later ….. )




 
 Any issues or suggestion please do comment...



Above is answer to following questions
How to open local database in SQL server 2008?
How do I open a local SQL server database?
How to connect to local instance of SQL server 2008?
Connecting to the Database Engine SQLServer2008?
After installations how to start with SQL server 2008?
How to login to local SQL server database?




Tuesday, August 21, 2012

How to write a Store procedure in SQL server database (Microsoft) with output parameter and transaction


This is the article which explains how to write a Store procedure in SQL server database with output parameter to extract the recorded id which is just inserted.

Background: A table is created with name “CD” and parameter as  

CDID: Primary Key with auto increment active on this parameter
CD_Number : It stores the CD number marked on CD as achieves
CD_Name: It stores the name of CD
CD_Descp: It stores the Details about CD’s


Create the store procedure as follows:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
Create PROCEDURE CD_Insert_CDdata
(
     @CD_Number nvarchar(50)= null       -- if no values are passed, then this parameters are  set to null
    ,@CD_Name nvarchar(300)= null
    ,@CD_Descp nvarchar(max)= null
    ,@mode nvarchar (5)= '1'
    ,@CDID nvarchar(50)=null OUTPUT       -- imp note : output keyword is needed to make the parameter act like output (it can act as output as well as input too)

)
 AS
BEGIN

    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

        IF (@mode ='1')
            BEGIN TRY
               BEGIN TRANSACTION    -- Start the transaction

                    -- insert Data In Cd table
                       INSERT INTO CD (CD_Number,CD_Name, CD_Descp)
                                 VALUES (@CD_Number,@CD_Name,@CD_Descp)                  
                       
                   SET @CDID = Scope_Identity()
                    --SET @CDID = (Select Scope_Identity() as CDID)   -- (one more way)
               select 'success'  -- to send success as return value
               -- If we reach here, success!
               COMMIT

            END TRY
            BEGIN CATCH

              -- OMG, there was an Error/Exception….
              IF @@TRANSCOUNT > 0
                 ROLLBACK  --rollback the insert query above

              -- Raise an Exception /error with the details of the exception
              DECLARE @ErrorMsg nvarchar(4000), @ErrorSeverity int

              SELECT @ErrorMsg = ERROR_MESSAGE(),
                     @ErrorSeverity = ERROR_SEVERITY()

              RAISERROR(@ErrorMsg, @ErrorSeverity, 1)

                SET @CDID = @ErrorMsg + ' failed'

                    select 'failure'

            END CATCH   

        End

Note:
-          1. Here @CDID is acting like a output parameter. To make it as output parameter, keyword “output” is important to mention while declaring variables or otherwise it is accepted as input parameter by default.
 
-          2.In Sqlserver 2005 and  sql server 2008, if parameter is declared as output with keyword as “Output”, then that parameter acts like both input as well as output parameter. This means you can send the values to Procedure via parameters or also set the values to parameter in Store procedure.

-          3. But there is a small change in declaring a parameter in ADO.NET as output / In/out parameter
System.Data.SqlClient.SqlParameter CDID_param = mSqlcmd.Parameters.Add("@CDID", SqlDbType.NVarChar, 50);   // this parameter is  used to get the record number inserted
            // a.    CDID_param.Direction = ParameterDirection.Output; 
             //b.    CDID_param.Direction = ParameterDirection.InputOutput;
a > tells you that CDID_param ( as "@CDID” ) is only a Output parameter and cannot be used to pass the value to store procedure
b>> tells you that CDID_param ( as "@CDID” ) is Output as well as input parameter, you can either pass or retrieve value via parameters.


-          4. Use “Scope_Identity()”  because it returns the ID of latest inserted records in given table in store procedure   in same scope (same connection, same user, same table ) and do not gives any other ID…. While in case of @@IDENTITY returns the most recently created identity for your current connection, not necessarily the identity for the recently added row in a table.(largely affected by trigger , @@identity returns trigger affected table’s ID).

-          5. I used a Transaction always for DDL statements like insert update delete , so if anything goes wrong in middle , it revoke the inserts by rollback statement and the database is clean without incomplete /incorrect data.

-          6. Transaction is very essential and important in case of multiple table / row  insert  or update. If there are more than 1 statements to be executed one after another and if in middle any statements throws a Exception / Error in whole transaction, then all the updates/ inserts/deletion on database in that transaction should be rollback, this keeps database consistent, correct and clean.

SIMPLE : How to insert and retrieve data in Microsoft SQL Server database using ASP.net

This is a very basic and easy way to insert the data in database, this method suggest a proper way to insert the data in sql database.

Create the store procedure as follows:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[CD_Insert_CDdata]
(
     @CD_Number nvarchar(50)= null
    ,@CD_Name nvarchar(300)= null
    ,@CD_Descp nvarchar(max)= null
    ,@mode nvarchar (5)= '1'
    ,@CDID nvarchar(50)=null OUTPUT    -- imp note : output keyword is needed to make the parameter act like output (it can act as output as well as input too)
)
 AS
BEGIN

    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

        IF (@mode ='1')

            BEGIN TRY
               BEGIN TRANSACTION    -- Start the transaction

                    -- insert Data In Cd table
                       INSERT INTO CD (CD_Number,CD_Name, CD_Descp)
                                 VALUES (@CD_Number,@CD_Name,@CD_Descp)                  
                       
                   SET @CDID = Scope_Identity()  -- get the last inserted record ID (primary key)

                    --SET @CDID = (Select Scope_Identity() as CDID)   -- (one more way)
               select 'success'  -- to send success as return value

               -- If we reach here, success!
               COMMIT

            END TRY

            BEGIN CATCH

              -- OMG, there was an Error/Exception….

              IF @@TRANSCOUNT > 0

                 ROLLBACK  --rollback the insert query above

              -- Raise an Exception /error with the details of the exception

              DECLARE @ErrorMsg nvarchar(4000), @ErrorSeverity int

              SELECT @ErrorMsg = ERROR_MESSAGE(),
                     @ErrorSeverity = ERROR_SEVERITY()

              RAISERROR(@ErrorMsg, @ErrorSeverity, 1)

                --SET @CDID = @ErrorMsg + ' failed'  -- send the error message by parameter

                    select 'failure'   -- send a Failure response in return string

            END CATCH   

        End

Create a Class file in Asp.net project

Create and initialize the variables as the data needs to be instered in database.Initialize the SQL Objects to insert the data, create a function (or get /set method) to assign the data to variables. Assign the data to variables. Then create a function to insert the data named as “InsertCDData()”

public string InsertCDData()
    {   
        string strResult = null;   // used to send success or  failure values are return
        string strCDID = null;   // used to get the record number of inserted record!!!!

//initialize the Sqlconnection object
        using (mSqlCon = new SqlConnection(this.strConnection))
        {

            mSqlCon.Open();      // open the connection
           //initialize the SQLCommand object
            using (mSqlcmd = new SqlCommand())
            {
              mSqlcmd.Connection = mSqlCon;
              mSqlcmd.CommandText = "CD_Insert_CDdata";   //store procedure name
              mSqlcmd.CommandType = CommandType.StoredProcedure;

              mSqlcmd.Parameters.Add("@CD_Number", SqlDbType.NVarChar, 10).Value = this._CD_Number;

              mSqlcmd.Parameters.Add("@CD_Name", SqlDbType.NVarChar, 10).Value = this._CD_Name;

              mSqlcmd.Parameters.Add("@CD_Descp", SqlDbType.NVarChar, 10).Value = this._CDDescption;

              mSqlcmd.Parameters.Add("@mode", SqlDbType.NVarChar, 10).Value = "1";

              System.Data.SqlClient.SqlParameter CDID_param = mSqlcmd.Parameters.Add("@CDID", SqlDbType.NVarChar, 50);   // this parameter is  used to get the record number inserted

              CDID_param.Direction = ParameterDirection.Output;  
 
              //CDID_param.Direction = ParameterDirection.InputOutput;

                try
                {
                    mSqlDr = mSqlcmd.ExecuteReader();  // execute the store procedure

                    string strOutput = "";

                    while (mSqlDr.Read())
                    {
                        strOutput = Convert.ToString(mSqlDr[0]);  //to get the result generated from store procedure
                    }

                    mSqlDr.Close();

                    // to get The record ID just inserted
                    strCDID =  Convert.ToString(CDID_param.Value);

                    // OR this way  to ---  get The record ID just inserted
                   // strCDID = Convert.ToString(mSqlcmd.Parameters["@CDID"].Value);

                    if (strOutput.Contains("success"))
                    { // result is successful

                        strResult = "CD data Inserted Successfully!!!!!" + " Record No : " + strCDID;

                    }
                    else
                    {
                        if (strOutput == string.Empty)
                        {   
                            // result is Failure
                            strResult = "CD data Inserted Failure!!!!! ";
                        }
                        else
                        {    
                            // result is send out
                            strResult = strOutput + " Record No : " + strCDID + " Record Inserted !!";
                        }
                    }
                }
                catch (Exception ex)
                {  
                       // save the Exceptions created in Class files in database
                    StoreExceptions(ex);
                }
                finally
                {
                           // close all connection and null the objects created to release memory
                    mSqlCon.Close();

                    if (mSqlCon != null) //If con object is not null then Free memory occupied by msqlcon by Dispose it
                        mSqlCon.Dispose();
                    if (mSqlcmd != null)
                        mSqlcmd.Dispose();
                    if (mSqlDa != null)
                        mSqlDa.Dispose();

                    mSqlCon = null;   //free memory occupied by MsqlCon and msqlCmd and mSqlDa
                    mSqlcmd = null;
                    mSqlDa = null;

                }

                return strResult;  // return the result

            }
        }
    }

Tuesday, August 14, 2012

Computer hardware and cables shops in PUNE (a big fat computer/ electronics goods valley in PUNE)

Good Electronics and Computer Hardware shops In Pune.

Recently I faced an issue with my computer. I brought a new cabinet from Zeberonics. I switched from Mini cabinet to mid tower cabinet.  I started shifting my internal components of cabinet from older to newer cabinet. In process, I stuck with issue, as my new cabinet has bottom placement of PSU (SMPS), my PSU Cables (from PSU to Motherboard) were insufficient to reach the connection on motherboard.  Mainly my ATX +12 V cable from SMPS (PSU) was getting short to reach motherboard terminal. Thus to resolve this issue I searched on Google and I found a solution as to buy an “ATX12V 4-Pin CPU Power Extension Cable”.
I found it on Indian sites to purchase and I found one on theitdepot.com as “Lian Li ATX Extension Adapter Cable (PW8-8)” and “Nzxt 8Pin Motherboard Individually Sleeved Extension Cable (CB 8P)", both are above 350/- + shipping and having length as 30 cm and 25 cm each.  So before purchasing it from online store, I thought to just check out with local stores in Pune.
I searched a lots of computer vendors like data care center (DCC), BABA electronics, S-tech computers, Vardhaman computers etc, but none have any. Some of them shown me the SMPS (PSU) Power cable (from PSU to mains) instead and some say such cable never comes, or have to buy new SMPS (also shown the picture of cable and pin of cable by my mobile). Even the shops having computer repairing in-house says there is nothing as extension for such cable.
Finally a guy from Vardhaman computers suggested it will be available in Computer hardware shops in main Area of Pune named as budhwar peth. So I went there and saw a big fat computer/ electronics goods valley there and I was astonished. There were vendors selling computer parts/speakers/HDD/ mobiles to chips / transistors and diodes. There were hobby electronics kit store too. (In short it is like lamination road area, Mumbai)
So I start searching for my extension cable there on Saturday (Sunday closed), and initially I didn’t get the require cable but was getting references of shops that might have those cable.  Finally I went to a Cable shop, which makes the cable as per your requirement, with the male-female plugs you need and gives it to you.
That shopkeeper shown me the varieties of the connectors and I found mine, so he found the suitable female connector for same and ask me the length of cable to be made. He also asked for the number of quantity he wants, I said , I want just one for my P.C (:-P :-P).  He said that the person who cramps the cable is out of town and will take 2-3 working days to get the require cable made and deliver. I was ready to wait and paid him 100 Rs (in advance) and ask to call me once it is made.
Hoping that cable should be made soon and I will be able to start my pc again…
Shop name and address is as follows: (hope it helps others)

Smeeta Connectronics Pvt Ltd
House of Connectors,cables,switches and networking products
Address: 1st floor, Dhanvant Plaza, inside  Vasant cinema building, shop no : 598,near dagdushet mandir, budhwar peth,Pune 411002
TEL :: 020-24483796 / 020 – 24485327 / 020 66017610
Some other electronics shops

All in one Mobile parts /accessories store:
Geeta Sales
505 B, budhwar peth, Nityanand market, pune 411002
No: 02024497425
(I got a body of Samsung 3530 model which is not available in whole pune area except this store.)
There are some more … I will let you know…

Thursday, August 2, 2012

Why didn’t I get 1 Mbps Speed when I have 1 Mbps Plan Broadband?

Many of my friends discuss with me, about some typical issue with their broadband speed as , they have 1 Mbps (or so on) plan with them at their home and still they are facing low download issue as  file is downloaded at 128 KBps only (as shown by Browser or there download accelerators).
They say ISP Cheat us and do not give displayed speeds on internet as promised in plans.
So I explained the concept to them about their miss-understanding in Broadband Speed issue.
When you see that broaches of Internet Service Provider (ISP) like Vodafone etc , you will get that they are using the terms for Speed as “Mbps” or “Kbps”. So if they say they have plan giving 1Mbps, means it is having max speed of 1 mega bits per sec.  (Please note the alphabet “b”)  (This is known as download speed) 
While when we download anything from Internet, software and browsers uses different terms Like “MBps” and KBps”   (Please note the alphabet “B”) (This is known as transfer speed)
Note here 
Operators /ISP provider use terms as :-  Mbps: Mega bits per Sec.   (It uses small “b”) – Download speed.
Software/ browser use terms as: MBps : - Mega Bytes per Sec.       (It uses Capital “B”) – Transfer speed.
1 Byte = 8 Bits   :  DigitalElectronics Concepts.
1 KB = 1024 x 8 = 8192 bits
1MB =1024KB = 128 Kbits 

Thus when you have 1 Mbps plan means you will get max to max 1024/8 = 128 kbps
Likewise if you have plans like 512 Kbps or 2 Mbps, 4 Mbps you will get following speed 
Difference between Transfer speed and Download speed
128Kbps = 16 KBps (dial up connection/ ISDN)
256 Kbps = 32 KBps (DSL -Digital Subscriber Line, 2G networks- GPRS)
512 Kbps = 64 KBps (2.5 G, EDGE networks, leased Lines)
1 Mbps = 1024 Kbps = 128 KBps (cable broadband, ADSL, 3G, CDMA, UMTS)
2 Mbps =2048 Kbps = 256 KBps (cable broadband, ADSL, 3G……)
4 Mbps =4096 Kbps = 512 KBps (3G, Broadband services, wi-fi)
8 Mbps = 8192 Kbps = 1 MBps  
10 Mbps = 1.25 MBps

Time taken by a normal broadband service to download a file in MB/GB - detailed

This is the detailed version of the post "Time taken by a normal broadband service to download a file in MB/GB"


Broadband Speed / Connections
No of Hrs
 Max download with Full speed in Hrs (MB)
 Max download with Full speed in Hrs (GB)
1 Mbps
1 Mbps
1
450
0.4395
1 Mbps
2
900
0.8789
1 Mbps
3
1350
1.3184
1 Mbps
4
1800
1.7578
1 Mbps
5
2250
2.1973
1 Mbps
6
2700
2.6367
1 Mbps
7
3150
3.0762
1 Mbps
8
3600
3.5156
1 Mbps
9
4050
3.9551
1 Mbps
10
4500
4.3945
2 Mbps
2 Mbps
1
900
0.8789
2 Mbps
2
1800
1.7578
2 Mbps
3
2700
2.6367
2 Mbps
4
3600
3.5156
2 Mbps
5
4500
4.3945
2 Mbps
6
5400
5.2734
2 Mbps
7
6300
6.1523
2 Mbps
8
7200
7.0313
2 Mbps
9
8100
7.9102
2 Mbps
10
9000
8.7891
4 Mbps
4 Mbps
1
1800
1.7578
4 Mbps
2
3600
3.5156
4 Mbps
3
5400
5.2734
4 Mbps
4
7200
7.0313
4 Mbps
5
9000
8.7891
4 Mbps
6
10800
10.5469
4 Mbps
7
12600
12.3047
4 Mbps
8
14400
14.0625
4 Mbps
9
16200
15.8203
4 Mbps
10
18000
17.5781
8 Mbps
8 Mbps
1
3600
3.5156
8 Mbps
2
7200
7.0313
8 Mbps
3
10800
10.5469
8 Mbps
4
14400
14.0625
8 Mbps
5
18000
17.5781
8 Mbps
6
21600
21.0938
8 Mbps
7
25200
24.6094
8 Mbps
8
28800
28.1250
8 Mbps
9
32400
31.6406
8 Mbps
10
36000
35.1563
 10 Mbps
10 Mbps
1
4500
4.3945
10 Mbps
2
9000
8.7891
10 Mbps
3
13500
13.1836
10 Mbps
4
18000
17.5781
10 Mbps
5
22500
21.9727
10 Mbps
6
27000
26.3672
10 Mbps
7
31500
30.7617
10 Mbps
8
36000
35.1563
10 Mbps
9
40500
39.5508
10 Mbps
10
45000
43.9453
12 Mbps
12 Mbps
1
5400
5.2734
12 Mbps
2
10800
10.5469
12 Mbps
3
16200
15.8203
12 Mbps
4
21600
21.0938
12 Mbps
5
27000
26.3672
12 Mbps
6
32400
31.6406
12 Mbps
7
37800
36.9141
12 Mbps
8
43200
42.1875
12 Mbps
9
48600
47.4609
12 Mbps
10
54000
52.7344