Navigation

Search

Categories

On this page

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: 125
This Year: 63
This Month: 0
This Week: 0
Comments: 0

Sign In

 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.