.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 Query keeps failing on Where clause

Posted By:      Posted Date: August 31, 2010    Points: 0   Category :Sql Server
I am very new to SQL so forgive me for this. We are upgrading to Dynamics AX 2009 and in doing so I have been volunteered as the report writer. Lucky me. I have a query that should return all items for a customer and their resective OnHand quantity in one field and in another field it should only return an OnHand quantity if certain conditions are met in another field, in this case a location field (example; product in Embargo). Also this Embargo could be a variation of locations, (example) louembarg, embargff, louembargun, etc. I have cleaned my query back up since I believe my path was way off track. Below the query is an example of what the end result should be. SELECT     TOP (100) PERCENT dbo.INVENTTABLE.DATAAREAID, dbo.INVENTTABLE.CUSTACCOUNT, dbo.INVENTTABLE.CUSTDIVISIONID,                       dbo.INVENTTABLE.PACKAGINGGROUPID, dbo.INVENTTABLE.ITEMGROUPID, dbo.INVENTTABLE.ITEMID, dbo.INVENTTABLE.NAMEALIAS,                       dbo.INVENTTABLE.ITEMNAME, dbo.INVENTTABLE.STANDARDPALLETQUANTITY, dbo.INVENTTABLE.BOMUNITID, dbo.INVENTDIM.WMSLOCATIONID,            &n

View Complete Post

More Related Resource Links

SQL Query Where Clause



FROM dbo.SSD a , dbo.SSAAppEAL b
AND (a.AssocClaim = 1)
AND b.somedate = SELECT MAX (b1.somedate)
                   FROM dbo.SSAAppEAL b1
                   WHERE b1.SSN = b.SSN
                   AND b1.somedate < sysdate

When ever I add this Query to my Select Statement. SQL management studio is shutting down abruptly.

The mail fault is with this statement

b.somedate = SELECT MAX (b1.somedate)
                   FROM dbo.SSAAppEAL b1
                   WHERE b1.SSN = b.SSN
                   AND b1.somedate < sysdate

Can any one help me out


INSERT statement with OUTPUT clause, referencing outer query columns

I have a problem to solve and I have run into what appears to be a limitation of TSQL.  I have looked around and did not find much on this subject, so I apologize if this duplicates another post.  I am using SQL Server 2008. From what I have read on BOL, when you are performing a DELETE or UPDATE statement, you can reference unaffected columns from the outer query in the OUTPUT clause, but this is apparently not allowed in an INSERT statement. I am working on a process that will create new copies of existing records - essentially, the user can create a whole new copy of a set of records, and the process requires that I track both what the original PK values were and the corresponding PK values for the new rows. This example will hopefully spell out my problem.  This script shows two tables, [Primary_Object] and [Secondary_Object].  Not shown here are multiple tables that rely on [Secondary_Table], which is why I have to be able to track this info. This first script shows the setup of the tables involved and the data involved: /* create test data */ create table primary_object ( primary_object_id int identity(1,1), parent_object_id int, name char(1)) create table secondary_object ( secondary_object_id int identity, primary_object_id int, amount money) insert into primary_object (parent_object_id, name) select 0, 'A' insert into secon

Write select query with a paremetrized where clause, and populate database with the retrieved column

I want to be able to retrieve column values using the dropdownlist values as parameters then populate the tbPO table with the retreived values. Where and how do I do it. ImportsSystem.Data.OleDb ImportsSystem ImportsSystem.IO Imports ?directcostDataSetTableAdapters PartialClass po_header  Inherits System.Web.UI.Page  Dim cn As OleDbConnection  Dim cmd As OleDbCommand  Dim dr As OleDbDataReader  Dim icount As Integer  Dim str As String  Dim vendor_id As Object   ?  Public Sub btn_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.ClickTry   context.Items.Add(     cmd.CommandType = System.Data.   cmd.CommandText = Dim context As HttpContext = HttpContext.Current"Company_Name", DropDownList3.Text)Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\Owner\Documents\Visual Studio 2010\WebSites\WebSiteJun25\App_Data\directcost.mdb;")Dim cmd As New OleDbCommand()CommandType.Text"insert into tbPO(ponumber, suppliername, ShipTo, basictype, DateNeeded, Purpose,ShippingInstr, ProjId) values(?,?,?,?,?,?,?,?)" cmd.Parameters.AddWithValue( cmd.Parameters.AddWithValue( cmd.Parameters.AddWithValue( cmd.Parameters.AddWithValue( cmd.Parameters.AddWithValue( cmd.Parameters.AddWithValue( cmd.Parameters.AddWithValue( cmd.Parameters.Add

Query help to write case statement in Where clause?

Hi All, I have table something like this:- SELECT UserName, IsManager FROM Employee IsManager has only two values either 1 (which means user is a Manager) or 0 (which means user is not a Manager) Now I want to write below query:- DECLARE @IsManager INT SET @IsManager = 2 SELECT UserName, IsManager FROM Employee WHERE IsManager = CASE WHEN @IsManager = 1 THEN 1 WHEN @IsManager = 0 THEN 0 WHEN @IsManager = 2 THEN 1 | 0 ----- THIS IS NOT WORKING, when I set @IsManager value to 2 then where clause should be like this "IsManager = 1 OR IsManager = 0" END Can anybody help me out in modifying about query so that it produces both the results when @IsManager variable value "2". Thanks Regards, Kumar

How to pass string values to parameterized sql query in Clause?

Hi,I'm using parameterized sql query to get data from database string query = "Select * from employee where employee_city in (@value)";strign city ="'NewDelhi','Bangalore','Mumbai'";I'm using following code to achive thisDataSet ds = new DataSet();SqlConnection con = new SqlConnection("Server=localhost;....");SqlCommand cmd = new SqlCommand();cmd.CommandText =query;SqlParameter param = cmd.Parameters.Add("@value",SqlDbType.VarChar);param.Value = city;SqlDataAdapter dap = new SqlDataAdapter();dap.SelectCommand = cmd;dap.Fill(ds);But this is not giving the result.If run the query in SQLServer query window as "Select * from employee where employee_city in ('NewDelhi','Bangalore','Mumbai')", records are there.But the same query will not return any records from ADO.Net.How to solve this?Thanks,Ashokan

XPath Query in Where clause of SQL query

Hi, I have one table where one column contains XML format data inside and i have more than one row in my table.  i.e. <test><id>1</id></test> . . . . . <test><id>N</id></test> Here  the XML id could be upto N as shown above. Now i want to query on my table and in Where clause i want to put XPath Query on this column so that i could put a condition on specific ID and based on that iD i could get the whole data row from table, i am thinking query should be as below Select * from XYZ where col1.query('//test/id') >= 5 or Select * from XYZ where col1.value('(/test/id)[1]', 'int')>= 5 Here the first query where i am using col1.query('//test/id') >= 5, There is syntax error, and in second one, first of all.. i have to declare the XML type local variable then set that vaiable like  SET @localvariable = col1 from XYZ and then @localvariable.value('(/test/id)[1]', 'int'), eventhough i cannot put the range (>=,<=) here, as well as we cannot get the all rows in @localvariable when we set the value to the local variable. but i want my query should be as i show above. How can i do this ? Any suggestion.....  --Jai JP Sharma

Order By clause in RowNumber function slowing down the performance of my query.



I have a query which has a paging functionality and for which i'm using ROW_NUMBER() function. The order by clause in my rownumber function is dynamic and gets changed all the time when ever the sp is called. It works fine for few columns but for one column which is of datetime datatype, it takes lot of time. Amazing thing is with when i sort by the same column in descending order, the query runs in a sec but ascending order takes lot of time :(.

I tried creating a non clustered index(as i already i have a clustered index on that table) on that datetime column but it did not help me.

Could you please suggest what i can do to improve the performance.






FillBy failing, SQL query works

I changed a query for a bound datagridview.  Original the datagridview showed all the columns, but I removed some of the columns by rightclicking on the datagridview.  I changed the fillby query to only include certain columns I selected.  Now it isn't working.  The same query works in MS-SQL, but it doesn't work in Preview data in the dataset designer. Can someone give me an idea of how to look for where my error is?

Using CASE statement in "IN" clause of query


I have a sql datasource with the ControlParameter called ddlDropDownList.

2 questions:

1. Is my syntax below ok, I am getting a runttime error that the syntax is incorrect.

2. I have the select statement set up the control parameter to get the selected value from the dropdownlist as shown below, is that syntax correct?  especially the "selectedItem.value" for the propertyname property. thx

select fieldOne, fieldTwo from someTable where fieldOne IN 
CASE WHEN @ddlDropDownList='valueABC' THEN ('ABC') WHEN @ddlDropDownList='valueDEF' THEN ('DEF') 

<asp:ControlParameter ControlID="ddlDropDownList" Name="typeSlctd" PropertyName="SelectedItem.Value" Type="String" />

Group by Clause in Union Query


Table 1

Qty BatchNo MaterialCode

54 211 127

50 AR0347 165

252 054 190

180 022 191

50 HP10004 194

20 005010 196


Table 2

Qty BatchNo MaterialCode

6 211 127

28 054 190

20 023 191


Select Sum(iQty) as iQty ,vBatchNo,vMaterialCode




 a.iQty as Qty,      

 a.vBatchNo   as  BatchNo,      

 a.vMaterialCode &

Linq Query with dynamic where clause i.e filter with dynamic no of filter columns



I want a linq query with dynamic where clause.

Following is explanation of problem:


Following line returns me n no of rows.

IEnumerable<XElement>  xeleRows = (from xele in xdocFile.Root.Elements(strCtlLookUpXMLNode) select xele);

structure of xeleRows will be like:













Now I want to get one row from N Number of rows on basis of filter criteria that can be dynamic, the no of columns in filter criteria will vary at run time.

Anybody know shows to achieve this using Linq. Please guide.



MS SQL Server: Search All Tables, Columns & Rows For Data or Keyword Query

If you need to search your entire database for specific data, this query will come in handy.

So when a client needs a custom report or some sort of custom development using Great Plains, most of the time I will have to track down the data in the system by running this query and find the table(s) it is in.

How to Encrypt Query String Parameters in ASP.NET

Encrypt Query String Parameters in ASP.NET.u can send secure data one page another page u can also use query string to encrypt

Power of using Clause in SharePoint

The Using Clause will help to avoid memory leaks in SharePoint by automatically Disposing the MOSS objects.

For example when we create SPSite and SPWeb objects, if we don't dispose it explicitly it might create memory leaks,

Content Query Web Part missing in SharePoint 2010

If you don't see content query web part listed in the web parts list, this is because you have not enabled "Search Server Web Parts" feature in site collection features. Enable this feature and content query web part will show in the list of web parts.

sql query that don't run



I'm going crazy... i've got a piece of code that don't update the database... Could somebody tel me why it doesn't run??

Dim conn As SqlConnection
        Dim cmd As SqlCommand
        Dim cmdstring As String = "Update Corsi Set [Contenuto]='" & TxtText.Content & "' Where [ID]='" & Request.QueryString("Id").Replace("'", "") & "'"
        conn = New SqlConnection(SqlAnni.ConnectionString)
        cmd = New SqlCommand(cmdstring, conn)

Need help with a linq to sql query


I want to display some stats in a listview contril.  The table contains a record for every impression and for every click, and every record has a datetime field for the time and date of the impression of click.  I want to be able to display how many impressions and clicks there were in a given day and hour, something like below:

Date              Time                              Impressions    Clicks
8/20/2010                                               450              14            
                     Midnight -1:00am               150               5

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