.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

SQL IN statement with variables

Posted By:      Posted Date: September 10, 2010    Points: 0   Category :Sql Server
Hi  Could anyone help me to write this more elegantly so it uses the IN statement to represent OR DECLARE @patient1 int, @patient2 int, @patient3 int Set @patient1=123, patient2=456, patient3=678 SELECT * FROM PATIENT_DETAILS WHERE PATIENT_ID=@patient1 OR PATIENT_ID=@patient2 OR PATIENT_ID=@patient3 So ideally I would like to have the WHERE statement written like this :- WHERE PATIENT_ID IN(@patient1, @patient2, @patient3) Should the IN statement work ok like this, with variables in? Also sorry for not showing the error I got but just peoples opinion is fine if anyone can help please. Also please forgive if there any slight syntax error above as I'm doing this example from memory (from when I was at work. Thanks Matthew Ps Could anyone recommend a way of being able to enter as many patient numbers as I like to declare them at the top of the SQL (and in the WHERE clause) without having to amend the code too much everytime I want to search for more patients numbers. Would I have to use the WHILE statement with arrays maybe - I have no idea with arrays in SQL if anyone can give me some pointers.

View Complete Post

More Related Resource Links

foreach statement cannot operate on variables of type 'object' because 'object' does not contain



Still struggling with this code Frown


I'm trying to follow an example in a book i'm reading, but the example is using linq to sql, i'm trying to use linq to xml. Problem is i get the following error:

Error 1 foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator' d:\MVC3_Website\Website.WebUI\Views\Home\Index.aspx 11 8 Website.WebUI


My code is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Website.Domain.Models.Weather.Entities
    public class WeatherForcast
        public string loc { get; set; }
        public string loc_id { get; set; }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using Website.Domain.Models.Weather.Abstract;
using Website.Domain.Models.Weather.Entities;

namespace Website.Domain.Models.Weather.Concrete
    public class WeatherRepository : IWeatherRepository
        public IEnumerable<WeatherForcast> GetWeatherCity(string strWeatherCity)

Temporary tables in SQL Server vs. table variables

When writing T-SQL code, you often need a table in which to store data temporarily when it comes time to execute that code. You have four table options: normal tables, local temporary tables, global temporary tables and table variables. I'll discuss the differences between using temporary tables in SQL Server versus table variables.

Passing Linq Statement between master and content page


I usually work with windows forms, and am just starting to work with ASP.Net, so appologies if this is a dumb question!

I have a master page which has a search button on it. The results of this are built up using a Linq statement and if there are any results, I want to display the results in a contents page.

On the masterpage, I have the following code:

Private _res

    Public Overridable ReadOnly Property SearchRes()
            Return _res
        End Get
    End Property

 Private Sub DoSearch()
   'some code to get a linq result

    If res.Any Then
            _res = res
            Server.Transfer("SearchResults.aspx", True)
            'no results
            LabelNoRes.Visible = True
        End If
 End Sub

On the SearchResults.aspx page I have this code.

Dim m As pxSite = CType(Page.Master, MasterPage)
        If m.SearchRes IsNot Nothing Then
            Label1.Text = "Results found = " & m.SearchRes.Count
        End If

m.searchRes is always nothing. 

What am I doing wrong here?


Session and Application Variables


I have a web application in which i need to logout the user if he clicks the logout button or even if he closes his browser window. On Logout button click, i am doing session.Abandon(), but how to go about his browser window close.

Can anybody help with a code sample.

ReportViewer :: Failed to enable constraints. But my statement is valid!!

  • A
  • n error has occurred during report processing.
      • Exception has been thrown by the target of an invocation.
        • Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

    Why do I keep getting this error, even when not using any data on the report. When I run the query in SQL server I get a resultset. However when I try to render the report I get this error.


    Whats wrong with this statement


    Im trying to updated some old ASP pages with some new .net pages and cant seem to get this update statement to work. I need to update the current ASP code below and then once thats working im going to use that same statement in a procedure for all our new .Net pages..

    So can anyone see what im doing wrong by inserting the 2nd column to the update statement?

    strSqual = "update tas set date_completed='" & TransDate & ", trans_id=" & InsertedTransID & "' where date_completed is null and sercontract_id="& strContractID & " and DATEDIFF(dd,task_due_date,'" & strProcDate & "')<=14"


    I am trying to add an extra column to the update, but not sure if the syntax is correct.

    If Statement Issue



    This is very strange to me. I have spent 2hrs looking into this inside out , but dont seem to get it

    I have an if statement that inserts data into the database. But i check to make sure the name is not entered twice. Now when the name is already in the db, then it should insert else put out a message saying its already in the db

    My code works fine except that  when its not in the db, its inserts but still puts out the message that says "Name is already in use" Not sure if am not seeing something. But thought i did bring it to the forum. Here is my code...Pretty simple

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click

            Dim objConnection As SqlConnection
            Dim objCommand As SqlCommand
            Dim strSQLQuery1 As String


            ' If there's nothing to Add for then don't search
            ' o/w build our SQL Query and execute it.
            If String.IsNullOrEmpty(txtAdd.Text) Or Leadbank.SelectedValue = "000" Then


    statement cannot appear outside of a method body


    hi all,

      i am posting my vb.net problem .plz tell me how to resolve this :-

    Dim conn As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
        'Dim mysqlconnection As New SqlConnection(conn)
        'If mysqlconnection.State=ConnectionState.closed Then mysqlconnection.Open();
        'Dim mySqlcommand As New SqlCommand("select CategoryId,CategoryName from Categories", mysqlconnection)
        'Dim mySqlDataAdapter As New SqlDataAdapter(mySqlcommand)
        'Dim mydataSet As New DataSet()

        'if mysqlconnection.State=ConnectionState.closed Then mysqlconnection.Open();

    i m getting 5 errors in this code

    declaration expected in mySqlDataAdapter.Fill method; Gridview1.DataSource=ds; Gridview1.DataBind();

    how to multiple condition in if statement in asp.net C#



    i am using if condition to find out a time

    if(time=="08 AM)


    response.write"shift A";


    but problem is how can i put multiple condition in if like

    if(time=="06 AM" and "08 AM" and "07 AM")



    Hello, i need help changing the following code into a switch...case statementUndecided

    <script runat="server">
    void Page_Load()
        if (Page.IsPostBack)
        public String toSring()
        int intcomputerChoice=1;
           if (Page.IsPostBack)

    Can IronPython use dynamic variables?


    I am building a small application that can

    1. Dynamically load 2 text boxes on a web form

    2. Build a logic on those textboxes in IronPython to sum them and return the result.

    3. I have already built a IPY script that does some opearions on a static text boxes. How to build a script on the dynamic textboxes?

    Windows With C++: X64 Debugging With Pseudo Variables And Format Specifiers


    This month we explain how pseudo variables and format specifiers provide a wealth of information for use in debugging.

    Kenny Kerr

    MSDN Magazine December 2008

    Using a If Else Statement


    I'm working in a Wizard control and need a little help. I'm pulling in a labels text through a databound field and if it equals a certain text then I need a textbox field to be less than or equal to a certain amount. I would also like to have a message appear to prompt the user that an invalid number has been entered. I'm not sure how to go about this. Is it better to use client side javascript or use page load and perform some kind of control validation. The code I've tried isn't working so any help would be greatly appreciated.

    For instance...

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

    If label1 = "Refrigerator" then

    TextBox1 <= "700"

    Else Label1 = "Washer" then

    TextBox1 <= "500"

    End if

    End Sub

    The statement terminated. The maximum recursion 100 has been exhausted before statement completion.


    Hi All

    I have the below sql scripts that give me the error:
    "The statement terminated. The maximum recursion 100 has been exhausted before statement completion."

    Ive tried using OPTION ( MAXRECURSION 0 ) or 1000 but it still  give me the same error.

    WITH cte as (SELECT     ticketid, setstatus, setdate, row_number() OVER (partition BY (ticketid)
    ORDER BY setdate ASC) AS rn
    FROM         [OneForm].[dbo].[TFAM_SLA_Times]
    SELECT     TicketID, 'Submitted', SubmittedON, 0
    FROM         [OneForm].[dbo].vw_TFAM_ALL)
        SELECT     a.ticketid, SUM(OneForm.dbo.[CalcMinutesSLA_TFAM](a.setdate, b.setdate)) AS SLA_in_Min
         FROM         vw_TFAM_SLA_Combined AS a LEFT JOIN
                                vw_TFAM_SLA_Combined AS b ON a.ticketid = b.ticketid AND a.rn = b.rn - 1
         WHERE     (a.SetStatus = 'Submitted' OR
                                a.SetStatus = 'Acknowledged' OR
                                a.SetStatus = 'Pending')
         GROUP BY a.TicketID

    If i remove the call to the function [CalcMinutesSLA_TFAM] or the b.rn - 1 it works fine.

    Here is the code for the function:

    CREATE FUNCTION [dbo].[CalcMinutesSLA2

    Where to place if statement


    I have a design problem I could use some help determining how to code this problem.

    I have a table with 3 fields, catCode, startDate and endDate. I am having trouble deciding how to query my DB based on the following...

    By default a gridview will return all records that match the catCode selected from a dropdown list.


    If the user checks a check box, only records are returned where....

    startDate <= today AND endDate >= today


    How can I apply the If condition to compare when the check box is selected? I used the wizard to build the select statment for the gridview, but I can switch that to a SP if that makes life easier.


    Thanks for any and all help and suggestions.

    ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
    Sql Server  SharePoint  Silverlight  Others  All   

    Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend