.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

Select second query if first query returns no rows

Posted By:      Posted Date: October 14, 2010    Points: 0   Category :Sql Server


I need to return result of the second select statement if the first select statement returns nothing:

-- First statement
SELECT Salesmen.SalesmanID, Salesmen.FullName, 
  Salesmen.AssignedAppointments, Salesmen.Picture, 
FROM Appointments INNER JOIN
  Salesmen ON 
  Appointments.SalesmanID = Salesmen.SalesmanID
WHERE (Appointments.Closed = 1)
ORDER BY Salesmen.AssignedAppointments
-- Second statement
FROM Salesmen
ORDER BY AssignedAppointments

View Complete Post

More Related Resource Links

Query returns correct rows but I am not able to concatenate the rows into a variable :(


Hi all,

Why in the code below I am able to list all rows and display the field 'stepID' but I am not able to concatenate them all in the variable @stepIds?

declare @date as datetime
set @date = '2010-09-20 23:01:20:000'
declare @instance as uniqueidentifier
set @instance = '04658F34-CBF1-4CCD-A683-F23BDB669D35'

  Declare @CrLf char(2)
  Set @CrLf = Char(13) + Char(10)
	Declare @stepIds varchar(8000)
	Set @stepIds = ''
		--@stepIds = @stepIds + ' - Step: ' + CONVERT(varchar(4), stepID)

Select second query if first query returns nothing



How can I SELECT second if first SELECT returns nothing?


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.

On New Item form, select item on choice dropdown based on query result.


I posted this on Experts Exchange awhile back with no answer, so here's hoping someone here has an idea :)

So I've mostly figured this problem out, but I need some help in getting over the hump... note that I'm using JavaScript to do this (SPServices) on SharePoint 07'.

I'm on the New Items page of a list. Based on a user's selection in a "Teacher" dropdown, I'm doing the following:

1.) Get the value of the Teacher field and several other fields (School and Visit Date)
2.) Run a CAML query based on those fields to find the last list item entered for that Teacher

So here's where I'm stuck...

I have 10 choice fields, all with choices 0, 4, 7, and 10. Depending on what they were set to in the last entered item (which I queried), I want to set the selected item on each of those dropdowns to equal that. So "Score 1" was set to "4" on the la

select query


Hi All.

I have 2 table.


ID  | Person_Name

1   |  abc

2   |   def

3   |   ghq


ID  | Product  | ExportPersonID  | ImportedPersonID |  OwnerID

1    |   a         |   1                      |   2                           |  3

2    |  B          |    2                     |   3                           |  1

I want above two table output

ID    Product      |  ExpotedPerson|    ImportedPerson  |  Owner

1          a       &n

condition Select query

Hi All.Greetings.I have 1 table.Table 1ID | Name  | Sex       |  DateofBirth1   | abc    | Female  | 19802   |abc2   | Female  |20083   |abc3   |Male       |19854   |abc4   |Male      | 2009I want to see if age is greater then 3 year it will adult girl or adult boy. and If age is less then 3 year then it will be child girl or child boy.I have Output like thenName | Sex         |abc    | Adult girl |abc2  | child girl  |abc4  | child boy | etc.....How to write condition query to get my result.Thanks in Advance.

Any way to execute a workflow when a caml query returns zero items?

Lets say I have a list with a status column and I want to execute a workflow when all items in the list have a status of complete. I basically want to execute a workflow when the caml query looking for non-complete statuses returns zero rows. Can I do this with SPD or are there any 3rd party tools for this? I'm thinking of writing one if there are not.


Hi Everone,    Can any one help me out in creating a dynamic select statement, so far my SP look like belowALTER PROCEDURE [dbo].[CheckAccess]@TABLENAME VARCHAR(100),@JNID INT=0ASBEGIN    SET NOCOUNT ON;    DECLARE @SQ VARCHAR(500)    DECLARE @ID INT =0     SET @SQ= ' SET @ID = SELECT TOP 1 ID FROM ' +  @TABLENAME + ' WHERE PID ='+ @JNID       PRINT @SQ    EXEC(@SQ)       IF (@ID>0)      BEGIN        RETURN 1      END    ELSE      BEGIN        RETURN 0      ENDENDGOlet me know where i am going wrong

ODBC Select if Statement in MAS90 query

Hi, I am connecting to a MAS90 database via DSN and am having trouble with the query string for ODBC.  I can collect most all fields if I SELECT them directly, however, I want to create a result column based on which cost is higher. As far as I know, this select statement in to and ODBC connection needs to comply with MSSQL I have tried SELECT IM1_InventoryMasterfile.ItemNumber, IFF(IM1_InventoryMasterfile.LastCost > IM1_InventoryMasterfile.AveCost,IM1_InventoryMasterfile.LastCost,IM1_InventoryMasterfile.AveCost) as 'Cost', IM1_InventoryMasterfile.TotalQtyOnHand FROM IM1_InventoryMasterfile IM1_InventoryMasterfile And SELECT IM1_InventoryMasterfile.ItemNumber, CASE WHEN IM1_InventoryMasterfile.LastCost > IM1_InventoryMasterfile.AveCost THEN IM1_InventoryMasterfile.LastCost ELSE IM1_InventoryMasterfile.AveCost END as 'Cost', IM1_InventoryMasterfile.TotalQtyOnHand FROM IM1_InventoryMasterfile IM1_InventoryMasterfile Neither are working?  What am I missing here? Can I do this sort of if then statement in MSSQL?   Thanks for your help 

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

Tricky SELECT query from a Single Table

Hi I have a 2 rows of data in a table as mentioned below   Table1             ElementID Month Year Planned Cost UnplannedCost PlannedExpense UnPlannedExpense 4 9 2010 NULL 40 NULL 20 4 9 2010 400 NULL 200 NULL  I need a SELECT query to get the output in a single row as ElementID Month Year Planned Cost UnplannedCost PlannedExpense UnPlannedExpense 4 9 2010 400 40 200 20 Could anybody help me in writing a query for this? Thanks

Analysis Services - Query returns a #error result

Hi, I have a cube - which i had backed up and just retored it. After the restoration, when i try to reply the cube e.g: select [Time].&[200503] on 0 , {[Process].[All process]} on 1 from [myConsolidations] - i recieve an a result showing #error only. What could be the cause of this?

How to Create an MDX Query Parameter to Select 30 Values from a Dimension?

Hi, I'm using SSRS 2005 to report on an SSAS cube that contains a Procedure dimension.  I don't need to use members of this dimension in my report, but rather need to select records (patients) where their chart has one or more of the codes.  I've researched this today and cannot locate the best approach.  Thus far, I've attempted to create an MDX query parameter as part of my dataset.  However, I don't know whether this is the correct approach, and how to structure the syntax so that only records with one or more procedures are included in the report?  If so, what is the proper MDX syntax for setting my Procedure code equal to the query parameter? Thanks, Sid

Returning rows not found in inner query

select * FROM [C_Accessioning].[HL7].[GMessages] where MessageID not in (Select MessageID from HL7.ORM_MSH) There are two rows of data in GMessages: MessageID MessageDateTime              Filename 28             2010-09-07 16:29:02.543    ORM1.hl7 29             2010-09-07 16:29:07.547    ORM2.hl7 There is no data in ORM_MSH. Please see sql statement copied above. The inner query returns null, I am expecting that the query return both rows from GMessages, but it does not return any rows. Please let me know how to fix.   Thanks,Deep

Select and update in same query

Hi all, I need to update the selected rows from a select statement and update it using an update query. For that the query i am using is UPDATE SERVERACCOUNTSTRAN..TRAN_JOURNALDET SET CONTRATRANSACTIONHEADCODE=T.CODE FROM ##TRAN TR INNER JOIN SERVERSSRETAIL..TRANSACTIONHEAD T ON T.SHORTNAME=TR.CREDT_ACCT WHERE T.COMPANYCODE=1 AND CONTRATRANSACTIONHEADCODE=0 Now the problem is all the values of contratransactionheadcode field is updated to 18. But the real values are different for each row. only the first row value is 18 which is updated to every other row. Thanks in advance.Sujith Kumar www.sujithkumar.tk

Query to return TOP n with 'Other' grouping for all remaining rows

Hi all, I've been given a specific type of report to produce, and am having difficulty in getting my SQL right to return the data as needed. I need to return TOP n Categories based on amount of sales (which I can do) but then a final category with a sum of all other sales. The purpose would be to capture all of the small sales values into one 'Other' category so that the chart I'll produce does not have lots and lots of small-value columns. I found the following post which seems to come close: SELECT TOP 10 CompanyID, CompanyName, SUM(GrossSales) [GrossSales] FROM CompanySales GROUP BY CompanyID, CompanyName ORDER BY SUM(GrossSales) desc UNION SELECT -1, 'Other' [CompanyName], SUM(GrossSales) [GrossSales] FROM CompanySales WHERE CompanyID NOT IN ( SELECT TOP 10 CompanyID, CompanyName, SUM(GrossSales) [GrossSales] FROM CompanySales GROUP BY CompanyID, CompanyName ORDER BY SUM(GrossSales) desc ) But this gives a syntax error on UNION, which I'm guessing is due to the ORDER BY clauses. However I think the ORDER BY is needed to ensure I return the results in the correct order. Does anyone have any ideas of how to do this? Thanks for any assistance Matt

Error in select query

Hi, I am tring to use the following command but getting the following error message --Query Select * from CTOR_DBPF\Amord_wrk\dbo.rate2010 Server:   CTOR_DBPF Database: Amord_wrk Table:    rate2010 --Error message Line 1: Incorrect syntax near '\'.
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