Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Using the "IF EXISTS" conditional statement.

Posted on 2007-04-06
8
Medium Priority
?
271 Views
Last Modified: 2012-05-05
I'm trying to gather some user statistics based on 3 conditions. First I want to check if the referring querystring is already in the database. If not insert it into the db. Second, if the querystring is already in the database, then check if the ip-address of the user is already in the database. If it is, then check if the ip address was inserted today. If not, update the "refCountIn" field with +1. The problem lies in the third condition where we check if the ip-address was inserted today and if false, update the "refCountIn" field with +1 and if true, do nothing.Below is the code I have until now:  

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        ' *** Declare the variables
        Dim getStatCmd As String
        Dim updStatCmd As String

        Dim myRef As String = Request.QueryString("ref")
        Dim myQueryString As String = Request.ServerVariables("QUERY_STRING").Replace("ref=", "")
        Dim myRemoteAddr As String = Request.ServerVariables("REMOTE_ADDR")
        Dim myHttpReferer As String = Request.ServerVariables("HTTP_REFERER")

        Dim dtNow As Date = DateTime.Now
        Dim dtToday As Date = DateTime.Today

        ' *** Conditional INSERT command
        getStatCmd = _
            "IF EXISTS(SELECT 'True' FROM tblReferers WHERE robotName = '" & myQueryString & "' AND refIpAddress = '" & myRemoteAddr & "') " & _
            "BEGIN " & _
            "SELECT 'This clickin has already been recorded!'" & _
            "END ELSE BEGIN " & _
            "SELECT 'Clickin recorded' " & _
            "INSERT INTO tblReferers(robotName, refIpAddress, refReferer, refTime) " & _
            "VALUES(" & _
             "'" + myQueryString + "'," & _
             "'" + myRemoteAddr + "'," & _
             "'" + myHttpReferer + "'," & _
             "'" + dtToday + "')" & _
            "END "


        ' *** Conditional UPDATE command
        updStatCmd = _
            "IF EXISTS(SELECT 'True' FROM tblReferers WHERE robotName = '" & myQueryString & "' AND refIpAddress = '" & myRemoteAddr & "' AND refTime > '" & dtToday & "') " & _
            "UPDATE tblReferers " & _
            "SET refCountIn = refCountIn + 1, refTime = '" & dtToday & "' " & _
            "WHERE refIpAddress = '" & myRemoteAddr & "' AND robotName = '" & myRef & "'"

        Dim insConnCmd As New SqlCommand(getStatCmd, New SqlConnection(connSD))
        Dim updConnCmd As New SqlCommand(updStatCmd, New SqlConnection(connSD))

        insConnCmd.Connection.Open()
        insConnCmd.ExecuteNonQuery()
        insConnCmd.Connection.Close()

        updConnCmd.Connection.Open()
        updConnCmd.ExecuteNonQuery()
        updConnCmd.Connection.Close()

    End Sub

Anyone with an idea on how to solve this one? I think I need to write a subquery for the third condition, but I don't have a clue on how to handle this.Thanks in advance for your help!
0
Comment
Question by:Rineau
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 23

Expert Comment

by:Racim BOUDJAKDJI
ID: 18864526
I suggest you use encapsulate your SQL code in stored procedures instead of leaving it in the API code.  It will make it more readable and debuggable...
0
 
LVL 35

Expert Comment

by:YZlat
ID: 18864589
what you have will not work as an inline sql statement. Create a stored procedure like Racimo suggested
0
 
LVL 4

Author Comment

by:Rineau
ID: 18865099
Thanks guys!
I have just written my very first stored procedure :) Is this correct?

ALTER PROCEDURE sdstats.spGetReferers
      
      (
      @myQueryString varchar(50),
      @myRemoteAddr varchar(12),
      @myHttpReferer varchar(155),
      @dtToday datetime
      )
      
AS
      BEGIN
      SET NOCOUNT ON
      
      IF EXISTS(SELECT 'True' FROM tblReferers WHERE robotName = @myQueryString AND refIpAddress = @myRemoteAddr)
      BEGIN
      SELECT 'This clickin has already been recorded!'
      END ELSE BEGIN
      SELECT 'Clickin recorded'
      INSERT INTO tblReferers(robotName, refIpAddress, refReferer, refTime)
      VALUES(@myQueryString, @myRemoteAddr, @myHttpReferer, @dtToday)
      END
      
      IF EXISTS(SELECT 'True' FROM tblReferers WHERE robotName = @myQueryString AND refIpAddress = @myRemoteAddr AND refTime > @dtToday)
    UPDATE tblReferers SET refCountIn = refCountIn + 1, refTime = @dtToday
    WHERE refIpAddress = @myRemoteAddr AND robotName = @myQueryString
      END
      RETURN

How do I pass data/execute the stored procedure from the codebehind? Any good tutorials or something?
0
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 
LVL 23

Expert Comment

by:Racim BOUDJAKDJI
ID: 18865184
I suggest you use following style in coding...(sp are very practical.  You may either return an output parameter or a dataset or both:))

ALTER PROCEDURE sdstats.spGetReferers
     
      (
      @myQueryString varchar(50),
      @myRemoteAddr varchar(12),
      @myHttpReferer varchar(155),
      @dtToday datetime,
      @return_value int output
      )
     
AS
      BEGIN
      SET NOCOUNT ON
     
      IF NOT EXISTS(SELECT 1 FROM tblReferers WHERE robotName = @myQueryString AND refIpAddress = @myRemoteAddr)
            BEGIN
                  set @return_value = 0
      END
      ELSE
      BEGIN
                  INSERT INTO tblReferers(robotName, refIpAddress, refReferer, refTime)
            VALUES(@myQueryString, @myRemoteAddr, @myHttpReferer, @dtToday)
            set @return_value = 1
      END
     
      IF EXISTS (SELECT 1 FROM tblReferers WHERE robotName = @myQueryString AND refIpAddress = @myRemoteAddr AND refTime > @dtToday)
      BEGIN
            UPDATE tblReferers SET refCountIn = refCountIn + 1, refTime = @dtToday
            WHERE refIpAddress = @myRemoteAddr AND robotName = @myQueryString
            set @return_value
      END
      RETURN
0
 
LVL 4

Author Comment

by:Rineau
ID: 18868872
Thank you Racimo, but there seems to be an error in the syntax of the stored procedure. It's in the update part of the code. Visual Studio returns the error: "Incorrect syntax near the keyword 'END'".

I also made a start with the code for exectuting the strored procedure. Does it appear to be correct?

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim sqlConnSD As New SqlConnection("connStrSD")
        Dim trackCmd As New SqlCommand("trackReferer", sqlConnSD)

        Dim myQueryString As String = Request.ServerVariables("QUERY_STRING").Replace("ref=", "")
        Dim myRemoteAddr As String = Request.ServerVariables("REMOTE_ADDR")
        Dim myHttpReferer As String = Request.ServerVariables("HTTP_REFERER")
        Dim dtToday As Date = DateTime.Today

        trackCmd.CommandType = CommandType.StoredProcedure

        trackCmd.Parameters("@myQueryString").Value = myQueryString
        trackCmd.Parameters("@myRemoteAddr").Value = myRemoteAddr
        trackCmd.Parameters("@myHttpReferer").Value = myHttpReferer
        trackCmd.Parameters("@dtToday").Value = dtToday

        sqlConnSD.Open()
        trackCmd.ExecuteNonQuery()
        sqlConnSD.Close()

End Sub

ps: for what it's worth; I raised the number of points to 500

0
 
LVL 23

Accepted Solution

by:
Racim BOUDJAKDJI earned 2000 total points
ID: 18869031
Ooops..forgot to set up the last return value  Besides I suggest you separate update/insert/selects in different sp's for manageability...

ALTER PROCEDURE sdstats.spGetReferers
     
      (
      @myQueryString varchar(50),
      @myRemoteAddr varchar(12),
      @myHttpReferer varchar(155),
      @dtToday datetime,
      @return_value int output
      )
     
AS
      BEGIN
      SET NOCOUNT ON
     
      IF NOT EXISTS(SELECT 1 FROM tblReferers WHERE robotName = @myQueryString AND refIpAddress = @myRemoteAddr)
            BEGIN
                  set @return_value = 0
      END
      ELSE
      BEGIN
                  INSERT INTO tblReferers(robotName, refIpAddress, refReferer, refTime)
            VALUES(@myQueryString, @myRemoteAddr, @myHttpReferer, @dtToday)
            set @return_value = 1
      END
     
      IF EXISTS (SELECT 1 FROM tblReferers WHERE robotName = @myQueryString AND refIpAddress = @myRemoteAddr AND refTime > @dtToday)
      BEGIN
            UPDATE tblReferers SET refCountIn = refCountIn + 1, refTime = @dtToday
            WHERE refIpAddress = @myRemoteAddr AND robotName = @myQueryString
            set @return_value = 2
      END
      RETURN
0
 
LVL 4

Author Comment

by:Rineau
ID: 18869053
Thanks very much Racimo! Greatly appreciated!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question