Navigation

Search

Categories

On this page

Saving an Array to a Database
Creating an Array or String from Database Records
Howto: use MySql with .Net
A SQL Query to Find Duplicate Values
SQL: Preventing Duplicate Records In a Database In a Signup Form
AJAX: Populating a selectbox with results from a database
SQL Server CASE-WHEN Statement
Welcome to my Weblog

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 112
This Year: 50
This Month: 0
This Week: 0
Comments: 0

Sign In

 Thursday, June 07, 2007
Thursday, June 07, 2007 11:54:16 AM (Eastern Standard Time, UTC-05:00) (  |  )

I really like this example because it illustrates just how powerful client-side and server-side technology used in conjunction can be.  My javascript function, saveSelectedtoDatabase, passes a few parameters to my .aspx page saveSelected.aspx.  The string passed is in the form saveSelected.aspx?UserID=2447&BenchmarkName=Benchmark1&CompanyName=IBM*Ford Motor*AMD&CompID=14575*17411*41522

function savedSelectedtoDatabase(intUserID,benchmarkName,thistext,thisvalue)
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support the XMLHttpRequest object.")
return
}
var url="saveSelected.aspx?UserID="+intUserID+"&BenchmarkName="+benchmarkName+"&CompanyName="+thistext+"&CompID="+thisvalue;
xmlHttp.onreadystatechange=stateChanged5
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

 

saveSelected.aspx takes the querystring value passed to it and splits the CompanyName and CompID values by * and then saves each record to a SQL Server database.

<script runat="server">

Sub Page_Load()
If Not IsPostBack Then

Dim intUserID As Integer
Dim strBenchmarkName As String
Dim strCompID As String
Dim strCompanyName As String

'These values are coming from the AJAX function savedSelectedtoDatabase()
intUserID = Request.QueryString("UserID")
strBenchmarkName = Request.QueryString("BenchmarkName")
strCompID = Request.QueryString("CompID")
strCompanyName = Request.QueryString("CompanyName")

'Remove trailing * characters
strCompID = strCompID.Substring(0, strCompID.Length - 1)
strCompanyName = strCompanyName.Substring(0, strCompanyName.Length - 1)

'Place these values into an array
Dim arrCompID As String() = Nothing
arrCompID = strCompID.Split("*")

Dim arrCompanyName As String() = Nothing
arrCompanyName = strCompanyName.Split("*")

'Get the length of one element of the array so we now how many times
'to loop through the database with updates/inserts
Dim i As Integer
Dim myArrayLength As Integer = (arrCompID.Length - 1)

'Insert new record into TBenchmarker and output parameter as BenchmarkID
'TBenchmarker requires UserID and BenchmarkName

Dim strSQLConn As SqlConnection
Dim cmd As SqlCommand
Dim SqlText As String

strSQLConn = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
            
Try    
strSQLConn.Open()
'Insert new record into TBenchmarker
SqlText = "benchmarkerAddRecord"
cmd = New SqlCommand(SqlText, strSQLConn)
cmd.CommandType = CommandType.StoredProcedure

'input parameters for the sproc
cmd.Parameters.AddWithValue("@UserID", intUserID)
cmd.Parameters.AddWithValue("@BenchmarkName", strBenchmarkName)

'Output parameter from sproc benchmarkerAddRecord which is SCOPE_IDENTITY
'Create a SqlParameter object to hold the output parameter value
Dim intNewBenchmarkID As New SqlParameter("@RETURN_VALUE", SqlDbType.Int)

'Set Direction as Output
intNewBenchmarkID.Direction = ParameterDirection.ReturnValue

'Finally, add the parameter to the Command's Parameters collection
cmd.Parameters.Add(intNewBenchmarkID)

'Execute the sproc
cmd.ExecuteScalar()

'Now you can grab the output parameter's value...
Dim intNewBenchmarkIDValue As Integer = Convert.ToInt32(intNewBenchmarkID.Value)

'Insert new record(s) into TBenchmarkerSaved
For i = 0 To myArrayLength
SqlText = "saveBenchmarkValues"
cmd = New SqlCommand(SqlText, strSQLConn)
cmd.CommandType = CommandType.StoredProcedure

'input parameters for the sproc
'intNewBenchmarkIDValue is the value returned from the sproc benchmarkerAddRecord
cmd.Parameters.AddWithValue("@BenchmarkID", intNewBenchmarkIDValue)
cmd.Parameters.AddWithValue("@CompID", arrCompID(i))
cmd.Parameters.AddWithValue("@CompanyName", arrCompanyName(i))
cmd.ExecuteNonQuery()
Next i
            
strSQLConn.Close()

'This value gets returned back to savedSelectedtoDatabase and added
'as an option to ddlSavedBenchmarks dropdown
Response.Write(strBenchmarkName & "#" & intNewBenchmarkIDValue)

Catch ex As Exception
Response.Write("There was an error when saving these companies. Please try again.")
Finally
        
End Try

End If        
End Sub

</script>

Thursday, June 07, 2007 10:23:55 AM (Eastern Standard Time, UTC-05:00) ( )

I've been working on a project which inolved a lot of javascript and one requirement was to grab a list of industry values and their primary keys, place them into an array or string and then return those back to my javascript function.   In this first example I use the StringBuilder() method which I guess from user feedback is much more efficient than creating a ArrayList object.

<script runat="server">
Sub Page_Load()
Dim strSQLConn As SqlConnection
Dim strSqlText As String
Dim cmd As SqlCommand
'Dim myList As New ArrayList
Dim dr As SqlDataReader
Dim count As Integer
Dim mySB As New StringBuilder()

strSQLConn = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
strSqlText = "getIndustries"
cmd = New SqlCommand(strSqlText, strSQLConn)
cmd.CommandType = CommandType.StoredProcedure

Try
strSQLConn.Open()
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

With dr
If dr.HasRows Then
While dr.Read
mySB.Append("{")
mySB.Append(dr.GetInt32(0))
mySB.Append("#")
mySB.Append(dr.GetString(1))
mySB.Append("}")
count += 1
End While
End If
End With

Finally
dr.Close()
strSQLConn.Close()
End Try

Dim strResults As String
strResults = mySB.ToString().TrimEnd(",".ToCharArray())
Response.Write(strResults)
End Sub

In this second example, I do the identical thing except that I use an ArrayList

<script runat="server">
Sub Page_Load()
Dim strSQLConn As SqlConnection
Dim strSqlText As String
Dim cmd As SqlCommand
Dim myList As New ArrayList
Dim dr As SqlDataReader
Dim count As Integer

strSQLConn = New SqlConnection(ConfigurationSettings.AppSettings("CorpLibConnectionStringCurr"))
strSqlText = "getCompanyNames"
cmd = New SqlCommand(strSqlText, strSQLConn)
cmd.CommandType = CommandType.StoredProcedure

Try
strSQLConn.Open()
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)

With dr
If .HasRows Then
While .Read
myList.Add("{")
myList.Add(.GetInt32(0))
myList.Add("#")
myList.Add(.GetString(1))
myList.Add("}")
count += 1
End While
End If
End With

Finally
dr.Close()
strSQLConn.Close()
End Try

Dim i As Integer

For i = 0 To myList.Count - 1
Response.Write(myList(i))
Next

End Sub


</script>

Thursday, June 07, 2007 10:14:11 AM (Eastern Standard Time, UTC-05:00) ( )

Tim Mackey's Weblog entry explains this nicely

http://tim.mackey.ie/HowtoUseMySqlWithNet.aspx

Thursday, June 07, 2007 10:11:39 AM (Eastern Standard Time, UTC-05:00) ( )

SELECT <KEY_COLUMN>, COUNT(*)
FROM <TABLE>
GROUP BY <KEY_COLUMN>
HAVING COUNT(*) > 1

 Wednesday, June 06, 2007
Wednesday, June 06, 2007 1:26:16 PM (Eastern Standard Time, UTC-05:00) ( )

I use this on signup forms to prevent a user from registering a second account with the same email address.

CREATE Procedure sp_AddSubscriber
@Name as nvarchar(50),
@Email as nvarchar(50),
@AddSubscriber varchar(255) OUTPUT

AS
 IF (SELECT COUNT(Email)
                  FROM TSubscribers
                  WHERE Email = @Email) = 0
  
  BEGIN INSERT TSubscribers
  (Name, Email)  Values  (@Name, @Email)
SET @AddSubscriber = "True"                           
END              
ELSE
     SET @AddSubscriber = "The email address you have entered has already been registered in our database."
GO

 Tuesday, June 05, 2007
Tuesday, June 05, 2007 1:06:17 PM (Eastern Standard Time, UTC-05:00) ( )

I've been working on a project that's involved a lot of javascript and AJAX development.  This basic idea was to call a .aspx page which queried a database, placed the results in an array, returned the array to the client and then split out the array and populated the select box.  This is how I did it.

First create the XMLHTTPObject

function getIndustries()
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Your browser does not support the XMLHttpRequest object.")
return
}

Call getindustries.aspx

var url="getIndustries.aspx"
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}

This displays a 'Please Wait message and icon to the user while the transaction is occuring.

function stateChanged()

  if (xmlHttp.readyState == 0)
  {
document.getElementById("lblResults").innerHTML = "<img src='mozilla_blu.gif' alt='loading..please wait'> Please wait"; //loading
  }
  else if(xmlHttp.readyState == 1)
  {
document.getElementById("lblResults").innerHTML = "<img src='mozilla_blu.gif' alt='loading..please wait'> Please wait"; //loaded
  }
  else if(xmlHttp.readyState == 2)
  {
document.getElementById("lblResults").innerHTML = "<img src='mozilla_blu.gif' alt='loading..please wait'> Please wait"; //interactive
  }
  else if(xmlHttp.readyState == 3)
  {
document.getElementById("lblResults").innerHTML = "<img src='mozilla_blu.gif' alt='loading..please wait'> Please wait";
  }
  else if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  {
document.getElementById("lblResults").innerHTML = "";  
 
  // Clear the available listbox of any previous options
  document.choiceForm.available.length = 0; 

// Split the delimited response into an array  
  var s = xmlHttp.responseText;
  var re = new RegExp('{([^{}]*)}','g');
  var x = [];
  while (re.exec(s)){ 
   x.push(RegExp.$1.split('#'));
  }
 
 // Add the array options to the selectbox available
  var sel = document.forms['choiceForm'].elements['available'];
 for (var i=0, len=x.length; i<len; i++){
    sel.options[i] = new Option(x[i][1], x[i][0]);
    }
 
  }
}

function GetXmlHttpObject()
{
  var objXMLHttp=null
 
  try {
    objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP"); //later IE
  } catch (e) {
  try {
    objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); //earlier IE
  } catch (e) {
  objXMLHttp = null;
  }
  }
 
  if (objXMLHttp==null)
  {
    objXMLHttp=new XMLHttpRequest() //IE7, Firefox, Safari
  }
  return objXMLHttp
}

getIndustries.aspx

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>

<script runat="server">
    Sub Page_Load()
        Dim strSQLConn As SqlConnection
        Dim strSqlText As String
        Dim cmd As SqlCommand
        Dim myList As New ArrayList
        Dim dr As SqlDataReader
        Dim count As Integer
        Dim mySB As New StringBuilder()
               
        strSQLConn = New SqlConnection(ConfigurationSettings.AppSettings("CorpLibConnectionStringCurr"))
        strSqlText = "getIndustries"
        cmd = New SqlCommand(strSqlText, strSQLConn)
        cmd.CommandType = CommandType.StoredProcedure
       
        Try
            strSQLConn.Open()
            dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)                       
            
                        
            With dr
                If dr.HasRows Then
                    While dr.Read
                        mySB.Append("{")
                        mySB.Append(dr.GetInt32(0))
                        mySB.Append("#")
                        mySB.Append(dr.GetString(1))
                        mySB.Append("}")
                        count += 1
                    End While
                End If
            End With
           
        Finally
            dr.Close()
            strSQLConn.Close()
        End Try

    Dim strResults As String
    strResults = mySB.ToString().TrimEnd(",".ToCharArray())   
    Response.Write(strResults)
    End Sub


</script>

 

 

Tuesday, June 05, 2007 12:32:07 PM (Eastern Standard Time, UTC-05:00) ( )

I was recently working on a project where I had to return the larger of two values in my T-SQL code.  COALESCE would not work because often one of the two values was not NULL which COALESCE requires.  The solution ended up being relatively simple by using a CASE-WHEN statement like below.

CASE
  WHEN CEOAnnualBonus > CEOBonus THEN CEOAnnualBonus
  WHEN CEOBonus IS NULL THEN CEOAnnualBonus
  ELSE CEOBonus
END 
AS CEOBonusCombined,
CASE
  WHEN CEOOtherAnnualComp > CEOAllOtherCompensation THEN CEOOtherAnnualComp
  WHEN CEOAllOtherCompensation IS NULL THEN CEOOtherAnnualComp
  ELSE
  CEOAllOtherCompensation
  END 
AS CEOAnnualCompCombined 

Also, I learned about using ISNULL to return a different value when you encounter a NULL value in your data.  This helps clean it up at run time.

ISNULL(dbo.TBenchmarkTemp.ChairIndependent, '-') AS ChairIndependent

 

Tuesday, June 05, 2007 12:23:39 PM (Eastern Standard Time, UTC-05:00) ( )

I'll be using my Weblog mostly for personal use as a code library. Thanks for looking around.