Showing posts with label Sql Server 2005. Show all posts
Showing posts with label Sql Server 2005. Show all posts

Order by on Varchar field in sql server


Saturday, March 17, 2012

Hello Reader,

In this articles, i am going to explain you, how to use Order by on Varchar Fields in SQL Server,

Till now you might have implemented order by on Int Fields but you may find difficult to implement order by on Varchar fields.


In Image you can see, i have create one field with Name ONO as varchar(50)..

Now if you will do directly order by like shown below, then you will get wrong data.

This way is wrong for Varchar Field..
select * from db_product DP
order by ONO

You will get wrong data as Output..



The correct way is there..
select * from db_product DP
order by 
case 
    IsNumeric(DP.ONO) when 1 then 
        Replicate(Char(0), 100 - Len(DP.ONO)) + DP.ONO 
    else 
        DP.ONO 
end


Thanks Hope this post will help you, if yes please put comment below of this page,
Rajesh Singh,
Asp.Net Developer
Email: raj143svmit@gmail.com
Dobazaar (Dubai, UAE)
www.dobazaar.com


Change ConnectionString when database server is not working


Thursday, September 22, 2011

Hello Friends,

Sometime, you might have notice that, your hosting server is working fine but your database is not working due to which you
might be getting error on website and you might be loosing visitor and ranking in website..

This post is regarding that only, you can manage this issue by two database.

You can have two database at different server and you can call this in global.asax

first you can make ping to first database everytime and if its working you can call first server database and
if you find any issue or server is not working then you can switch to second server using below code..



    Dim connStatus As String
        Dim png As New Ping()
        Dim pr As PingReply = png.Send("221.256.357.36")
        connStatus = pr.Status.ToString()
        '--------------------

        If connStatus = "Success" Then
            If ConnString = "OldConnection" Then
                If ConfigurationManager.ConnectionStrings("oldconnection1").ConnectionString <> "" Then
                    ConnObj = New SqlConnection(ConfigurationManager.ConnectionStrings("oldconnection1").ConnectionString)
                Else
                    Throw New Exception("Connection String is Empty")
                End If
            Else
                If ConfigurationManager.ConnectionStrings("oldconnection2").ConnectionString <> "" Then
                    ConnObj = New SqlConnection(ConfigurationManager.ConnectionStrings("oldconnection2").ConnectionString)
                Else
                    Throw New Exception("Connection String is Empty")
                End If
            End If
        Else
            If ConnString = "newconnection" Then
                If ConfigurationManager.ConnectionStrings("newconnection1").ConnectionString <> "" Then
                    ConnObj = New SqlConnection(ConfigurationManager.ConnectionStrings("newconnection1").ConnectionString)
                Else
                    Throw New Exception("Connection String is Empty")
                End If
            Else
                If ConfigurationManager.ConnectionStrings("newconnection2").ConnectionString <> "" Then
                    ConnObj = New SqlConnection(ConfigurationManager.ConnectionStrings("newconnection2").ConnectionString)
                Else
                    Throw New Exception("Connection String is Empty")
                End If
            End If
        End If


Let me know, if you have any query..




Thanks Hope this post will help you, if yes please put comment below of this page,
Rajesh Singh,
Senior Asp.Net Developer
e-Procurement Technologies Ltd (India)
www.abcprocure.com 

SQL Server Query to Search Text in Stored Procedure


Monday, September 12, 2011

Hello Friends,

This post contains one query, by using that you can make search for any text in your Stored
Procedure Or Triggers,

Here is the query..


Use TempDatabase

SELECT ROUTINE_NAME, ROUTINE_DEFINITION 
FROM INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_DEFINITION LIKE '%proc_%' 
AND ROUTINE_TYPE='PROCEDURE'



Frist Select the Database by Use prefix,like below
use TempDatabase

Then copy this query in your query browser of SQL server,

SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%proc_%'
AND ROUTINE_TYPE='PROCEDURE'

and just press F5, to run this query

Let me know, if you have any query..



Thanks Hope this post will help you, if yes please put comment below of this page,
Rajesh Singh,
Senior Asp.Net Developer
e-Procurement Technologies Ltd (India)
www.abcprocure.com 
 
 

How to create Trigger in SQL server ?


Thursday, December 16, 2010

In this post you can see, how to create trigger in SQL server 2005/2008


ALTER TRIGGER t_XYZ_Update 
   ON  tbl_tableName1
   AFTER UPDATE
AS 
IF ( UPDATE (tableField1) OR UPDATE (tableField2) OR UPDATE (tableField3) OR UPDATE (tableField4))
    BEGIN
    SET NOCOUNT ON;
    
    DELETE FROM tbl_tableName2 WHERE FieldId=(select FieldId from inserted)
    print 'Row Deleted Successfully'
    END
GO



Name you trigger like below line

ALTER TRIGGER t_XYZ_Update


Assign the table name on which you have to perform operation like below line


ON  tbl_tableName1


Design when you want to allow this trigger to get fire, here let take after UPDATE operation.


AFTER UPDATE


If any of the tbl_tableName1 field like tableField1,tableField2,tableField3,tableField4 get updated outside by query or in SP, then this trigger will get fire and perform operation assign to this trigger, you can find when field get updated by below query,

 
IF ( UPDATE (tableField1) OR UPDATE (tableField2) OR UPDATE (tableField3) OR UPDATE (tableField4))



Here in below box, you can see the operation you want to perform when this trigger get fire, here we have used "inserted" table, whenever any of field found updated, same row is inserted in "inserted" table so by this table you can find which row is updated and you can make use of that rowid to perform other operation,

 
    BEGIN
    SET NOCOUNT ON;
    
    DELETE FROM tbl_tableName2 WHERE FieldId=(select FieldId from inserted)
    print 'Row Deleted Successfully'
    END



Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Senior Asp.Net Developer

Email: raj143svmit@gmail.com
e-Procurement Technologies Ltd (India)
www.abcprocure.com

Prevent table from drop and re-create during saving changes


Thursday, December 2, 2010

Hello Friends,

Problem : Whenever you make any changes in the table defination, when table is fill with data or rows,it does not allow you to delete or make any changes to table.


Solution : You might have faced this issue many times, when ever you make any changes in the table defination and you try to save changes, then you might have seen error messages as shown in below image.




So here is the steps by which you can avoid dropping of table or re-creating it again by using below steps..

Step 1. There is one option in sql server, which allow you to save your changes to table without droping it.

You just click on Tool option in top menu, See below images you can see from where you can go to tool option,




Step 2. Then click on "Option",
then you will be prompt with options Box, in that you will see left menu, in that explore "Designers" option.


After Exploring Designers option, just click on "table and database designer", you will see below screen

Step 3. In below snap, you can see the field in Red Box, just untick it, so that you can save change.



Untick - Prevent saving changes that require table re-creation


Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Senior Asp.Net Developer
Email: raj143svmit@gmail.com
e-Procurement Technologies Ltd (India)
www.abcprocure.com

Use of ROLLBACK in SQL server Stored Procedure


Wednesday, November 17, 2010

Use of ROLLBACK in SQL server Stored Procedure

You might have heard about ROLLBACK but you have never used it right ?

If you have used it, its well and good but if Not, then this blog might help you to know, how you can use ROLLBACK in your SP.

Suppose you want to use two insert statement, one by one.

You want to use, @@identity of first insert in another insert statement then this is the best method to go with.

Suppose you are doing first insert operation and some problem occure and any how you are not able to insert data in second table then there might be some database mapping issue.

so here, ROLLBACK can help you to avoid such database problem,

For example, you have used ROLLBACK in your SP, and you are doing first insert operation and if some problem occur and you are not able to insert in second table then ROLLBACk will undo your first insert operation also which will help to avoid database mapping issue.


Below is the syntax of ROLLBACK,


BEGIN TRY
    BEGIN TRAN
    BEGIN
        'You insert statement
                            
        COMMIT TRAN
                    
    END
END TRY
 
BEGIN CATCH
    BEGIN
        ROLLBACK TRAN
                    
        PRINT ERROR_MESSAGE()
    END
END CATCH




Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Senior Asp.Net Developer

Email: raj143svmit@gmail.com
e-Procurement Technologies Ltd (India)
www.abcprocure.com


How to give reference of other table to current table in fields?


Sunday, July 25, 2010

Hello friends,

Thanks for all your support, Please read this new post to know how to give reference of other table to current table in fields.

You can find if any table with this name is exist in database of not, if you found delete it and create this one.

To do this operation use this code,

--Table Name: XYZ_SongRequest

    IF EXISTS (SELECT * FROM SYSOBJECTS WHERE ID = OBJECT_ID('XYZ_SongRequest'))
        DROP TABLE XYZ_SongRequest
    GO


Now by using below code, you can create reference of other table let say, XYZ_User, XYZ_City, XYZ_Rj to table XYZ_SongRequest

--Table Name: XYZ_SongRequest

CREATE TABLE XYZ_SongRequest (
    iRequestID            BIGINT            NOT NULL PRIMARY KEY IDENTITY(1,1),
    iMemberId            BIGINT            NOT NULL CONSTRAINT FK_SongRequest_iMemberId References XYZ_User(iMemberID),
    iCityID                INT                NOT NULL CONSTRAINT FK_SongRequest_iCityID References XYZ_City(iCityID),
    iRjId                INT                NOT NULL CONSTRAINT FK_SongRequest_iRjId References XYZ_Rj(iRJid),
    sRequest            VARCHAR(1000)    NOT NULL, 
    dRequestDate        DATETIME        NOT NULL DEFAULT GETDATE(),
    dProcessDate        DATETIME        ,
    sStatus                Varchar(20)        CHECK(sStatus in ('Pending','Approved')) NOT NULL DEFAULT 'Pending' 
)
GO


Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Senior Asp.Net Developer

e-Procurement Technologies Ltd (India)
www.abcprocure.com


Where to put Connnectionstring in web.config file.




Hello bloggers,

Most of the developers have big confusion that, where to put connection string in web.config file,
So this article will teach you which portion you can use to write your connection string.
When you will open web.config file, you will find this tag
<connectionStrings />

Here what you can do is, just replace this string with below connectionstring.


Use this connectionstring when database is on other server or other computer.

<connectionStrings>
  
      <add name="conn" connectionString="Data Source=XYZ;Initial Catalog=DatabaseName;user id=UserId;password=Password; Max Pool Size=7500;Connect Timeout=200;" providerName="System.Data.SqlClient"/>
      
</connectionStrings>


when database is in your computer, you can use local database server.

<connectionStrings>

<add name="conn" connectionString="Data Source=localhost;Database=MyDB;Integrated Security=SSPI " providerName="System.Data.SqlClient"/>
      
</connectionStrings>


Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Senior Asp.Net Developer

e-Procurement Technologies Ltd (India)
www.abcprocure.com

Manually Reset Identity Column Value in SQL Server


Saturday, May 1, 2010

Problem : If you are creating any table and using an identity column to that table, then at first time, when you insert any row, then identity value will start like 1,2,3... and so on..

But if you delete all the row from the table and when you try to insert new row in same table, the identity value will start from last identity value.

For Example the last identity was 6, so after deleting all data, when you insert new row, the identity value will be 7.

So to reset the identity Column value, you can use this below code.


Syntax

DBCC CHECKIDENT ( <table name>,RESEED,<new value>)

QUERY 

DBDD CHECKIDENT ('tbl_rajesh',RESEED,1)


Explaination :
table name = Your table name should be entered here
RESEED = this is used to reset your identity value.
new value = Starting identity value

If you want to check current identity value of any table, you can use below query.


DBCC CHECKIDENT (’tablename’, NORESEED)


Explaination :
table name = Your table name should be entered here
NORESEED = This will avoid RESEED function.

Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Asp.Net Developer
Indianic Infotech Ltd (India)
rajesh@indianic.com

Solved : Microsoft SQL Server, Error:233


Friday, April 23, 2010

Issue : Microsoft SQL Server, Error:233

Solution :

Sometimes when you try to open sql server 2005 or 2008, after entering login details, you will be prompted by this below screen, telling "Microsoft SQL Server, Error:233", then you just get struck and restart you computer or even format the computer or uninstall sql server 2005 or 2008, but not getting any solution?



Please read below to find the solution to this issue.


At this time, what you need to do is, just open your network connection and just disable and enable once,as shown below and your problem solved, thats it. try to login again and you will be succussfully login.



Ya,i know you might be rubbing your head. i have even done that when i came to know the solution to this problem. but anyways finally you got solution to this problem.

Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Asp.Net Developer
Indianic Infotech Ltd (India)
rajesh@indianic.com






Steps to Create Web Services in C# and Sql Server


Thursday, February 11, 2010

Steps to Create Web Services in C# and Sql Server

Step 1: Create one website project in the visual studio

Step 2: Create one folder with name “WebServices” in the project.

Step 3: Right click on the folder and click on add new item, then select “ web services” file from the list, as shown in image below



Step 4: After creating file in folder, Webservices.asmx file will be created in the folder and a default folder with name “App_Code” will be added the project and new file with the name “Webservices.cs” file will be added to it automatically.

Step 5: Then create three class file in App_Code folder with name :

a.WebService_Class.cs
We will create all the function of database operation here. We will discuss this in detail below.

b.Webservice_Main.cs
In this class, we will store the generic list of web services data. We will discuss this in detail below.

c.WebServices_StoreLocalVariable.cs
In this class we will store all the local variables, so that we can speed up web services. We will discuss this in detail below.

WebService_Class.cs


You can add this code in this file


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using commonlib.Common;

/// <summary>
/// Summary description for WebService_Class
/// </summary>

namespace EuroCity
{

public class GetAllCityClass
{
#region "Fields"

private int iCityID;
private string sCityName;


DBManager DM = new DBManager(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
#endregion

#region "Properties"

public int ICityID
{
get { return iCityID; }
set { iCityID = value; }
}

public string SCityName
{
get { return sCityName; }
set { sCityName = value; }
}

#endregion

#region "Function"

public DataSet GetAllCity()
{
DataSet DSCity = new DataSet();
string SQL = "SP_GetAllCity";

try
{
DSCity = DM.ExecuteDataSet(CommandType.StoredProcedure, SQL);
}
catch (Exception ex)
{
ex = null;
}
finally
{
if (DSCity != null)
{
DSCity.Dispose();
}
}
return DSCity;
}
#endregion
}
}




Webservice_Main.cs


You can add this below code in this file.

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using EuroCity;
/// <summary>
/// Summary description for WebServices_Main
/// </summary>
namespace EurocityCards_Classes
{
public class WebServices_GetAllCity
{
public string ErrorMessage = "";
public bool IsError = false;

public List<GetAllCityClass> CityList = new List<GetAllCityClass>();
}
}



WebServices_StoreLocalVariable.cs


You can add this below code in this file

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for WS_EuroClass
/// </summary>
public class GetAllCityClass
{
#region Data Member
public string iCityID, sCityName;
#endregion
}


WebService.cs


Add Below code in the WebService.cs, that generated automatically in the App_Code file.



using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
using EurocityCards_Classes;
using System.Collections.Generic;
using System.Configuration;
using EuroCity;



/// <summary>
/// Summary description for WS_EurocityCards
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public WebServices_GetAllCity GetAllCity()
{
EuroCity.GetAllCityClass objcity = new EuroCity.GetAllCityClass();
DataSet dscity = new DataSet();
WebServices_GetAllCity WS_city = new EurocityCards_Classes.WebServices_GetAllCity();
dscity = objcity.GetAllCity();
objcity = null;
if (dscity != null && dscity.Tables[0].Rows.Count > 0)
{
WS_city.IsError = false;

List<GetAllCityClass> stateList = new List<GetAllCityClass>();

foreach (DataRow dtRow in dscity.Tables[0].Rows)
{
GetAllCityClass objcityName = new GetAllCityClass();
objcityName.iCityID = dtRow["catid"].ToString();
objcityName.sCityName = dtRow["Catname"].ToString();
stateList.Add(objcityName);

}

WS_city.CityList = stateList;
}
else
{
WS_city.ErrorMessage = "No record Found";
WS_city.IsError = true;
}

return WS_city;

}


}




Add Below code in the web.config file for the connection to the database


<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=YOURSQLSERVERNAME;Initial Catalog=YOURDATABASENAME;user id=YOURDATABASEUSERNAME;password=YOURDATABASEPASSWORD;" providerName="System.Data.SqlClient;Max Pool Size=7500;Connect Timeout=500;pooling=true"/>
</connectionStrings>




To make database connection you need to create SP for that, please find code below


Create one Database in your SQL Server, and create one table name “SiteCity”

-- For City  Details
IF EXISTS (SELECT * FROM SYSOBJECTS WHERE ID = OBJECT_ID('SP_GetAllCity'))
DROP PROCEDURE SP_GetAllCity
GO
CREATE PROCEDURE [SP_GetAllCity]
AS
BEGIN
SELECT CityID,CityName
FROM SiteCity
ORDER BY CityName ASC
END
GO



After Creating the project, just build your application and run in brower.

Follow the screen to get your output.

Web Services First View
You will see the web service name here, see below in the image,



After clicking to the web services name, you will see "Invoke button"
This is the button used to run the web services.See in the screen below



Then finally you will see the below screen as output, what you were in need of, just call this and make you application successfull.




Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Asp.Net Developer
Indianic Infotech Ltd (India)
rajesh@indianic.com

Failed to retrieve data for this request Error in SQL Server


Saturday, February 6, 2010

SomeTimes after formating your computer, when you install sql server 2008.

When you try to connect your database and click on database menu to see the list of database, you will find windows alert showing you this below error.




Microsoft SQL Server Management Studio

Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)

Additional information:

An exception occurred while executing a Transact-SQl statement or batch.(Microsoft.SqlServer.COnnectionInfo)

The server principal "DatabaseName" is not able to access the database "Birdiethis" under the current security context. (Microsoft SQL Server, Error:916)




Please read below to find, how to solve this problem,

There is nothing to worry about, mostly user use to uninstall sqlserver software and install it again. then also they feel same problem.

Follow this steps :

Step 1: Open your sql server 2008,connect to database.

Step 2: click on view option for the top menu panel,then click to Object Explorer Details,



Step 3: You will see a panel will open at the right hand side,

Step 4: Right click on the header part of that panel, and unselect all option, as shown in the image,



Step 5: This will solve that issue, and you can use sql server 2008 without any error.

That's it,


Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Asp.Net Developer
Indianic Infotech Ltd (India)
rajesh@indianic.com

How to use Trim() Function in SQL server 2005 ?


Tuesday, November 24, 2009

There is no perticular function like Trim in SQL server but you can achieve Trim like functionality by doing Left Trim and Right Trim, to get complete trimed Text.

LTRIM is used to : Trim Text form left hand side or in other word remove space form left hand side.
RTRIM is used to : Trim Text from Right hand side or in other word remove space form Right hand side.

Example :

You can Use this query directly in SQL Server 2005

SELECT    *
FROM view_rapdata_full_member_pull
WHERE LTRIM(RTRIM(First_Name)) +' '+ LTRIM(RTRIM(Last_Name))
like '%Rajesh Singh%'
or
LTRIM(RTRIM(Last_Name)) +' '+ LTRIM(RTRIM(First_Name))
like '%
Rajesh Singh%'


You can Use this query in C# code to make search.

SELECT    *
FROM view_rapdata_full_member_pull
WHERE LTRIM(RTRIM(First_Name)) +' '+ LTRIM(RTRIM(Last_Name))
like '%" + txtsearch.Text + "%'
or
LTRIM(RTRIM(Last_Name)) +' '+ LTRIM(RTRIM(First_Name))
like '%" + txtsearch.Text + "%'


Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Asp.Net Developer
Indianic Infotech Ltd (India)
rajesh@indianic.com

Retrive data from database using Stored procedure and class file in Asp.Net


Thursday, October 8, 2009

Step1: Create SP in database

-- =============================================

-- Author: rajesh

-- Create date: 6th Nov 2008

-- Description: this SP is to find the keyword used to do search.

-- =============================================

IF EXISTS (SELECT * FROM sysobjects WHERE id = object_id('JAU_SP_Getkeyword'))

DROP PROCEDURE JAU_SP_Getkeyword

GO

CREATE PROCEDURE JAU_SP_Getkeyword

(

@piMemberID INT

)

AS

BEGIN

select sTitle from JAU_Favouritesearch Group by sTitle

END

GO

Step2: call SP from class file

(1)à Create function in class file

ASP.net Code

'function made by rajesh for search

Public Function findkeyword() As DataSet

Dim objDBManager As New commonlib.Common.DBManager(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)

Dim keywordresult As New DataSet

Dim sSQL As String = "JAU_SP_Getkeyword"

Dim p(0) As SqlParameter

Try

p(0) = New SqlParameter("@piMemberID", _iMemberID)

keywordresult = Objdbmanager.ExecuteDataSet(CommandType.StoredProcedure, sSQL, p)

Dim str As String = Objdbmanager.ErrorMessage

Return keywordresult

Catch ex As Exception

ex = Nothing

End Try

End Function

(2)à Create property in class file

Public Property memberID() As Integer

Get

Return _iMemberID

End Get

Set(ByVal value As Integer)

_iMemberID = value

End Set

End Property

(3)à Declare _MemberID as protected in class file

Protected _iMemberID As Integer

Step3: call function defined in class file in aspx file

Dim objsearch As New Search /*Search here is class file name*/

/* By Below code you can use the data form the database */

'code done by rajesh to find keyword

Dim dskeyword As DataSet

dskeyword = objsearch.findkeyword()

Dim keywordtitle As String = Trim(Request.QueryString("Text"))

For i As Integer = 0 To dskeyword.Tables(0).Rows.Count - 1

Dim str As String = Trim(dskeyword.Tables(0).Rows(i).Item(0))

If str = keywordtitle Then

linkfav.Visible = False

End If

Next

'



Hope this post will help you,
if yes please put comment below of this page,
Rajesh Singh,
Asp.Net Developer
Indianic Infotech Ltd (India)
rajesh@indianic.com