Multiple Between Statement Not Returning

Aug 11, 2013

I have an SQL statement to find attractions between certain longitude and latitude values. The attraction i have already added to the database to test has values 51.502899 and 0.003552 for latitude and longitude. As you can see these values fall within the limits of the statement below but nothing is returned.

SELECT * FROM Attractions WHERE (Lat BETWEEN 51.51998 AND 51.49999) AND (Long BETWEEN 0.014 AND -0.006);

View 2 Replies


ADVERTISEMENT

Transact SQL :: Returning Multiple Values From Column In Select Statement?

Nov 26, 2015

I am writing a query and have the bulk of it already written. 

I am looking at a table that contains customer orders. There is a column named Customer_Order.Status Available values for this column is R, F, H, and C.

I'd like for my query to return all lines that have the value R, F, H.

My where clause is written like this 

WHERE CUSTOMER_ORDER.SITE_ID = 'XXX' AND CUSTOMER_ORDER.STATUS = ('R','H','F')

I know I'm missing something....

View 3 Replies View Related

Returning An IN Clause From A CASE Statement

Aug 8, 2006

Hi all,

I am passing in a variable into a CASE statement. Based on the value, I want to return a set of values in an IN clause. Here is an example:

(The where clause will use a field called 'Location')


DECLARE @strTest as Varchar(50)
SET @strTest = 'HI'

SELECT * FROM [SomeTable]
WHERE
CASE @strTest
WHEN 'HI' THEN Location IN('1', '2', '3')
END
ORDER BY Location


Is this possible to do?

Sanctos

View 1 Replies View Related

SQLRowCount() Returning -1 For SELECT Statement

Nov 13, 2007

Hi friends,
I am facing problem with SQLRowCount() function which is returning -1 when I tried to fetch records greater than 99 from my data file. if the data file contains total of 99 records then the above function is returning its second parameter value nRowCount as 99 but if dat file contains 100 records then it is returning nRowCount as -1
Please tell me whether it is a driver specic error or some thing else. I am using a ODBC driver for a database called MYOB.

Below is the piece of code that I used for fetching records.


if (SQLExecDirect(m_StmtHandle, (PUCHAR)sExecuteStatement.c_str(), SQL_NTS) != SQL_SUCCESS) return false;

if (SQLNumResultCols(m_StmtHandle,(SQLSMALLINT *) &nColumnCount) != SQL_SUCCESS) return false;

if (SQLRowCount(m_StmtHandle,&nRowCount) != SQL_SUCCESS) return false;

The string 'sExecuteStatement' in SQLExecDirect() function above is carrying a Select query that fetch 100 records.

Its strange that the function fails to return exact row count for 100 records, but it is working fine with 99 records.

I ma not using any kind of array with size of 99 or 100 in my code.

What I want to know is whether I can use SQLRowCount() with SELECT statement, If not what is the alternative.

Pleasee help me with a piece of code if you can.

Ishwar B.G

View 1 Replies View Related

Troubles Returning Values With SQL Statement -

Mar 28, 2006

Hi, I just want to know the following.

Is it posible to write a SQL statement that searches all values in a table where the

e.g:

"Jobid = 1" and sort the result set according to the "CategoryID"?

then if you want to display the values, you can populate them according to the "CategoryID"?



and then also write the result set to a "text file", and catagorize everything according to the "categoryID" in the following format???



Category Number: 8 Description: Site

Date Labour Hours Rate Subtotal

10/05/2005 Artisan 20 95.00 1,900.00
10/06/2005 Labourer 7 45 315.00


Category Total 2,215.00



And then after that the next "categoryid"

Thank You, I really hope you understand what I mean.

your help will be greatly appreaciated.

View 4 Replies View Related

SQLRowCount() Returning -1 When Used With SELECT Statement.

Nov 13, 2007

Hi friends,
I am facing problem with SQLRowCount() function which is returning -1 when I tried to fetch records greater than 99 from my data file. if the data file contains total of 99 records then the above function is returning its second parameter value nRowCount as 99 but if dat file contains 100 records then it is returning nRowCount as -1
Please tell me whether it is a driver specic error or some thing else. I am using a ODBC driver for a database called MYOB.

Below is the piece of code that I used for fetching records.


if (SQLExecDirect(m_StmtHandle, (PUCHAR)sExecuteStatement.c_str(), SQL_NTS) != SQL_SUCCESS) return false;

if (SQLNumResultCols(m_StmtHandle,(SQLSMALLINT *) &nColumnCount) != SQL_SUCCESS) return false;

if (SQLRowCount(m_StmtHandle,&nRowCount) != SQL_SUCCESS) return false;

The string 'sExecuteStatement' in SQLExecDirect() function above is carrying a Select query.

Its an unpredictable error because the function fails to return exact row count for 100 records, but it is working fine with 99 records.

I am not using any kind of array with size of 99 or 100 in my code.

What I want to know is:
1. Can I use SQLRowCount() with SELECT statement, If not what is the alternative.
2. Is this a driver specific error?.
3. Can I use SQL_DIAG_ROW_COUNT instead of SQLRowCount? If Yes, How to use it?.

Your help will be greatly appriciated if you give me a piece of code for this issue.

View 1 Replies View Related

Why Is This JOIN Statement Not Returning The Right Results?

Sep 19, 2007



Hi,
I have three tables:
1 Order Details
2 Product Info
3 Received Qty


The query is pretty simple however I'm getting incorrect results.

The query grabs a load of information (including a SUM statement) from the order details tbl.. this is INNER JOIN ed to the products tbl to match an ID field which grabs some extra info from the product info tbl.

all fairly straightforward and works without a problem..

However I now need to add in the received qty tbl (as the name suggests this keep a track of the qty's of items received)

I need to join this tbl to the order details tbl based on a unique ID from the orders tbl and then SUM together all of the entries in that received qty tbl for that item.

Result is I get a single record which shows the qty ordered (from the order details tbl), and the total received (from the received qty) tbl

These are held in a seperate tbl as an order can be deliveryed in several stages.



Here is my statement:

SELECT PDS_Login.Supplier_Products.ProductName, PDS_Login.Supplier_Products.ProductCode, dbo.Suppliers_POs_Details.POID,
dbo.Suppliers_POs_Details.PODetailsID, dbo.Suppliers_POs_Details.Qty, dbo.Suppliers_POs_Details.PricePerItem,
dbo.Suppliers_POs_Details.PoDetailsStatus, dbo.Suppliers_POs_Details.PoDateExpected, dbo.Suppliers_POs_Details.PODateReceived,
SUM(dbo.Suppliers_POs_Details.Qty * dbo.Suppliers_POs_Details.PricePerItem) AS LineTotal, SUM(dbo.Suppliers_POs_Details_Received.Qty)
AS QtyReceived
FROM dbo.Suppliers_POs_Details INNER JOIN
PDS_Login.Supplier_Products ON dbo.Suppliers_POs_Details.ProductID = PDS_Login.Supplier_Products.ProductID LEFT OUTER JOIN
dbo.Suppliers_POs_Details_Received ON dbo.Suppliers_POs_Details.PODetailsID = dbo.Suppliers_POs_Details_Received.PODetailsID
WHERE (dbo.Suppliers_POs_Details.POID = @POID)
GROUP BY dbo.Suppliers_POs_Details_Received.Qty, PDS_Login.Supplier_Products.ProductName, PDS_Login.Supplier_Products.ProductCode,
dbo.Suppliers_POs_Details.POID, dbo.Suppliers_POs_Details.PODetailsID, dbo.Suppliers_POs_Details.Qty, dbo.Suppliers_POs_Details.PricePerItem,
dbo.Suppliers_POs_Details.PoDetailsStatus, dbo.Suppliers_POs_Details.PoDateExpected, dbo.Suppliers_POs_Details.PODateReceived,
dbo.Suppliers_POs_Details_Received.Qty


The problem is, if there is more than one relating record in teh Received Qty tbl instead of that being added together as I want, two results appear...

It's obviously something simple but I can't seem to figure it out - anyone point me in the right direction?

View 3 Replies View Related

Returning Multiple Copies

Jan 13, 2006

I'm getting 3 copies of the result set expected, could someone take a look and tell me why. I know I covered this in school, but I can't remember the issue. Thanks


SELECT P.Quantity as Qty,
P.ItemID,
P.VendorCode,
P.Descr as Description,
P.UnitPrice as Price,
P.Amount,
I.Freight,
Rcvd = 0,
I.QtyRcvd as Ship
FROM PurchaseOrderItems P, ReceivedItems I, Received R
WHERE P.POID = R.POID AND R.IntRcdID = I.PRID AND P.POID = 193

View 2 Replies View Related

SELECT Statement Returning Nulls Unexpectedtly

Jun 14, 2008

All- Please assist: In this SELECT statement:
 1 SELECT person_id, (last + ', ' + first + ' on ' + CASE f.address_1 WHEN NULL THEN 'none' ELSE f.address_1 END) as last_first_address
2 FROM person
3
4 LEFT JOIN family f
5 ON person.family_id = f.family_id

I'm finding that the compound column last_first_address returns <null> when f.address_1 is null, even though it seems like it should return the string "none" per my CASE statement. If f.address_1 is not NULL, then it the statement works as expected. Please advise as to how I can fix the statement so that "none" is returned as the final string in last_fist_address if f.address_1 is null.
Note: I tried removing the parens. No effect on result. 
Thanks!
-Kurt
 

View 2 Replies View Related

Case Statement Returning Blank Results?

Sep 19, 2014

I have a query that pulls a list of organizations. I'm trying to use a CASE statement to add a column of names based on the relationship of the individual to that organization. It is possible for two people at the organization to both have that relationship to the organization. Currently, when I pull my results, I get all the individual's names for all the organizations, but I'm also getting a row where there is no name, something like:

Company1 ''
Company1 'Individual1'
Company1 'Individual2'

Some of the organizations, they have no one with the relationship, but for all the organizations that do have someone in the position I want to not see the blank row. My case statement is:

CASE WHEN EXISTS
(Select ind_customer.cst_key WHERE ixo_rlt_code = 'Relationship' )
THEN ind_customer.cst_ind_full_name_dn
ELSE ''
END
AS 'FULL NAME'

View 7 Replies View Related

Statement For Returning Stored Procedure Params

Oct 27, 2005

Hi all,I'd like to put together a SQL statement that will take the name of astored procedure as a param, and return that SP's parameters.I'm writing a test application, and I'd like to wrte a generator tosave myself some time, but I can't seem to figure out how to get theparams from a SP. Any help would be appreciated.Thanks in advance,Craig

View 2 Replies View Related

Returning Multiple Rows From 2 Tables

Aug 29, 2005

I have two tables and I want to return data from both. Currently my select statement is returning just 1 child record for each parent record and I want to return all child records that match the parent record.

Here's a sample of my tables/data/etc.

t1
------------
speciesid | species
1 | Mammals
2 | Rodents
3 | Reptiles


t2
---------
animalid | animal
3 | Skink
3 | Iguana
3 | Rattlesnake
2 | Meerkat
1 | Hippo
1 | Elk

What I want to do is pull up a list of all the species and under each list all the animals currently listed under that species.

So the result I want should look like:
Mammals (Hippo, Elk)
Reptiles (Skink, Iguana, Rattlesnake)
Rodents (Meerkat)

so currently I have:
SELECT A.animalid, S.speciesid, A.animal, S.species from t2 as A, t1 as S where S.speciesid=A.animalid order by species

this works great, it's just that it only returns one animal instead of all of the animals. Any help would be appreciated.

View 4 Replies View Related

Output Returning Multiple Lines

Sep 29, 2004

I am running this stored Prcedure and getting multiple lines for the output. Below are the queries the create the temp table (its holding the data), and the query that generates the output:

/* this creates the temp table */
Select count(*) as 'Donations', d_vst_id
into Donations_temp
from dnr_vst_db_rec
where convert(varchar(10),d_vst_date) between convert(varchar(10), @Beg_Vst_Date, 112) and convert(varchar(10), @End_Vst_Date, 112)
and d_vst_status = 'DN'
and d_vst_dontyp in ('E1', 'E2')
group by d_vst_id

/* this query generates the output */

select distinct cast(getdate() as varchar(30)) as 'TODAY'
,CONVERT(varchar(10), @Beg_Vst_Date,101) as 'BEGDTE'
,CONVERT(varchar(10), @End_Vst_Date,101) as 'ENDDTE'
,case Donations
when '1' then sum(1)
else 0
end as 'ONE1'
,case Donations
when '2' then sum(1)
else 0
end as 'ONE2'
,case Donations
when '3' then sum(1)
else 0
end as 'ONE3'
,case Donations
when '4' then sum(1)
else 0
end as 'ONE4'
,case Donations
when '5' then sum(1)
else 0
end as 'ONE5'
,case Donations
when '6' then sum(1)
else 0
end as 'ONE6'
,case Donations
when '7' then sum(1)
else 0
end as 'ONE7'
,case Donations
when '1' then Sum(0)
when '2' then Sum(0)
when '3' then Sum(0)
when '4' then Sum(0)
when '5' then Sum(0)
when '6' then Sum(0)
when '7' then Sum(0)
else Sum(1)
end as 'ONEA'
from Donations_temp
group by Donations

Thanks.

View 1 Replies View Related

Function Returning Multiple Values?

Mar 1, 2012

I have a table called tableA and i am fetching 10 rows from table.

select dept_id from tableA where branch = 'Chennai';

I got 10 records.

dept_id
-------
001
002
003
004
005
so n.....

Now i want to pass these dept_ids dynamically to a function parameter.

ie. exec function_name (@dept_id).

How do i write a function?

View 3 Replies View Related

T-SQL (SS2K8) :: Returning Multiple TOP Records?

Jul 10, 2014

Here is my setup: I have the following tables -

tblPerson - holds basic person data.
tblPersonHistorical - holds a dated snapshot of the fkPersonId, fkInstitutionId, and fkDepartmentId
tblWebUsers - holds login data specific to a web account, but not every person will have a web account

I want to allow my admins to search for users (persons) with web accounts. They need to be able to search by tblPerson.FirstName, tblPerson.LastName, tblInstitutions.Institution, and tblDepartments.Department. The only way a Person record is joined an Institution or Department record is through many -> many junction table tblPersonHistorical.

People place orders and make decisions in our system. Because people can change institutions and departments, we need an historical snapshot of where they worked at the time they placed an order or made a decision. Of course that means some folks will have multiple historical records. That all works fine.

So when an admin user wants to search for webusers, I only want to return data, if possible, from he most recent/current historical records. This is where I am getting bogged down. When I search for a specific webuser I simply do a TOP 1 and ORDER BY DateCreated DESC. That returns only the current historical record for that person/webuser.

But what if I want to return many different webusers, and only want the TOP 1 historical for each returned?

Straight TOP by itself won't do it.
GROUP BY by itself won't do it.

View 9 Replies View Related

Max Datetime Returning Multiple Results

Oct 23, 2013

I have a query running without issue on around 100,000 results however i have a couple where my MAX aggregate is returning two results for a MAX(date time) and i cannot figure out why. I have paired down the query to try and work it out but still don't know.

My query now looks like this (i have remove most columns)

SELECT STATUS, RunOn, sort, T_ID
FROM dbo.Results
WHERE (RunOn IN
(SELECT MAX(RunOn)
FROM dbo.Results
group BY T_ID) AND T_ID = 21405)

ORDER BY sort

I added the T_ID = 21405 to restrict the results to the problematic results, if i set T_ID to any other test result i get one value based on the latest RunOn, but for some reason with this T_ID i get two values, the latest one and one slightly older... The date time looks ok, i just can't work out why the latest and one older result are returned !

The original query was grouping by more items but i removed those to try and work out what is going one, as mentioned for 99.9% of results it works perfectly, but for this one i don't know.

View 10 Replies View Related

Returning Multiple Columns From One Db Column

Feb 24, 2008

How do I create a select query which returns multiple columns from one actual DB column?

DB structure
ID (int), photo (nvarchar(50)), name (nvarchar(50))

Sample data
1, 'photo1.jpg', 'john smith'
2, 'photo2.jpg', 'jane doe'
3, 'photo3.jpg', 'bob brown'
4, 'photo4.jpg', 'mary brown'
5, 'photo5.jpg', 'sue smith'
6, 'photo6.jpg', 'bob rogers'
...

Required output
pic_col_1, name_col_1, pic_col_2, name_col_2, pic_col_3, name_col_3
photo1.jpg, john smith, photo2.jpg, jane doe, photo3.jpg, bob brown
photo4.jpg, mary brown, photo5.jpg, sue smith, photo6.jpg, bob rogers

Normally, I would just query the data and have the client data loop over the dataset to create the required output, however in this application it is not an option...

Thanks,

Steve

View 3 Replies View Related

LIKE Using Subquery Returning Multiple Rows

Jan 30, 2008



This is probably very elementary to someone more experienced, but I'm having a hard time coming up with a way to do the following:


SELECT * FROM Transactions
WHERE MyField LIKE (SELECT MyValues FROM SearchValues)

But I can't because the subquery will return multiple rows. That's all I'm really trying to do - search all the rows in Transactions.MyField for any of the search values returned from the subquery.

And I can't restructure the SearchValues table to combine them into a single-row comma-delimited field or anything like that.

Any help would be appreciated-

Kenneth

View 11 Replies View Related

Query Returning Multiple Wrong Values

Jan 16, 2013

I've got this sql statement that keeps returning the wrong data. (it's related to a previous post, but is different)

Code:
SELECT C.NAME, OL.PART_ID, SL.SHIPPED_QTY
FROM CUSTOMER C
INNER JOIN USERS U ON C.ID = U.ID
INNER JOIN ORDERS O ON C.ID = O.ID
INNER JOIN ORDER_LINE OL ON O.ID = OL.ORDER_ID

[Code] .....

The qry pulls like this: (wrong way)

HTML Code:
company partID Qty
Acme Inc ABC123 3
Acme Inc ABC123 4
Acme Inc ABC123 100
Acme Inc KLM444 3
Acme Inc KLM444 4
Acme Inc KLM444 100
Acme Inc QRP456 3
Acme Inc QRP456 4
Acme Inc QRP456 100

It should be:

HTML Code:
Co. part Qty
Acme Inc ABC123 3
Acme Inc KLM444 4
Acme Inc QRP456 100

The Qty field has duplicates. I've tried various ways, but I cannot make this work.

View 14 Replies View Related

Returning Multiple Values From A Stored Procedure.

Feb 7, 2007

my stored procedure performs actions of deletion and insertion. Both the inserted and deleted items are output in temp tables with single column.
Is there a way to return the content of these two tables?
Is there a way to return a table from the stored procedure?

Thanks in advance
waamax

View 1 Replies View Related

Returning Multiple Rows From A Stored Procedure

May 22, 2006

Hi,I have the following stored procedure that does some processing andputs the result in a temporary table. I tried several things thatprocedure to display output that I can access with ADO.Net, but itdoesn't work. It doesn't even display the result in the query analyzerunless I add SELECT @ReturnFullNameAny help?The stored procedure:CREATE PROCEDURE sp_SEARCH_MULTIPLE_NAMES @search4fatherOfvarchar(255), @maximum_fathers int = 100, @ReturnFullName varchar(255)Output....SELECT @ReturnFullName = name FROM #FULLNAME------------------------------------------------To Execute the stored procedure:DECLARE @test varchar(255)EXEC sp_SEARCH_MULTIPLE_NAMES @search4fatherof='مريم',@returnfullname=@testPRINT CONVERT(varchar(255), @test)

View 5 Replies View Related

Sql Question - Returning Multiple Rows As One Record

Jul 20, 2005

Hi,In the process of localizing the 'regions' table, we added three newtables. The localized data will be stored in the TokenKeys andTokenValues tables. It would be easier if we did away with theTokeyKeys/TokenValues tables and just added a localeid in the regionstable, but this is the desired schema by the client. Here's theschema:Table: regionsid nameabbreviation1 United StatesUSTable: localesid locale1 en_US2 fr_CATable: TokenKeysid key1 db.regions.name2 db.regions.abbreviationTable: TokenValuesid keyid valuelocaleid1 1 Etas Unis22 2 EU2The old sql was simply this:select name, abbreviation from regionswhich returns:United States, USBut the new sql needs to link in the localized data from the tokeykeysand tokenvalues tables using the localeid... I’m trying to figure outwhat the sql statement would look like to return this:Etats Unis, EU (This is supposed to be the French version)My confusion is we are trying to return multiple column values fromthe same column (TokenValues.value) and make them act as separatecolumns in the same record, like it was with the original.Thanks

View 1 Replies View Related

Stored Procedure Returning Multiple Rows

Oct 23, 2007

I have a stored procedure which return a single value and one which return multiple rows between two colums.
In my code for the procedure which returns a single value i use (executescalar) which works fine.
I am not sure what command to use in my code when i am calling the stored procedure that returns multiple rows between colums.
Any help would be appreciated.
Thanks.

View 3 Replies View Related

Returning Multiple Results From A Cursor Into A Table

Sep 7, 2007

The problem I'm having is that I need a cursor to return multiple results into 1 .NET System.Data.DataTable, and I don't know if it's possible. Actually, the real problem I'm having is that whoever designed this database did a poor job and if it weren't for one small thing I could do this all with aggregates...

But more specifically, this is what I need to accomplish. I have written a cursor that I know works - when I run it in MS SQL Query Analyzer, I get the results I want, but it's returned in multiple tables. I am maintaining a .NET application with some pretty lousy performance and I'm trying to boost it up. I need to take the cursor's results, stuff them into a DataTable, and then return that table to my web application to render.

In my C# code, I am using a SqlDataAdapter to execute my query. This is what I'd like to do...





/*assume query is my working cursor, InvoiceDBConnection is not null, and dt is an empty, non-null DataTable*/

SqlDataAdapter sda = new SqlDataAdapter(query, InvoiceDBConnection);
sda.Fill(dt);

... but this doesn't work, and it makes sense, I guess...since the cursor returns multiple "tables" (not sure if that's actually how the data is returned).

So is there any way to accomplish what I want to do? Or do I have to do it the crappy way it's done now by running my aggregate query and then using a really time-consuming for loop on my results to make the necessary adjustment?

Any help is greatly appreciated

View 5 Replies View Related

Multiple Tables Used In Select Statement Makes My Update Statement Not Work?

Aug 29, 2006

I am currently having this problem with gridview and detailview. When I drag either onto the page and set my select statement to pick from one table and then update that data through the gridview (lets say), the update works perfectly.  My problem is that the table I am pulling data from is mainly foreign keys.  So in order to hide the number values of the foreign keys, I select the string value columns from the tables that contain the primary keys.  I then use INNER JOIN in my SELECT so that I only get the data that pertains to the user I am looking to list and edit.  I run the "test query" and everything I need shows up as I want it.  I then go back to the gridview and change the fields which are foreign keys to templates.  When I edit the templates I bind the field that contains the string value of the given foreign key to the template.  This works great, because now the user will see string representation instead of the ID numbers that coinside with the string value.  So I run my webpage and everything show up as I want it to, all the data is correct and I get no errors.  I then click edit (as I have checked the "enable editing" box) and the gridview changes to edit mode.  I make my changes and then select "update."  When the page refreshes, and the gridview returns, the data is not updated and the original data is shown. I am sorry for so much typing, but I want to be as clear as possible with what I am doing.  The only thing I can see being the issue is that when I setup my SELECT and FROM to contain fields from multiple tables, the UPDATE then does not work.  When I remove all of my JOIN's and go back to foreign keys and one table the update works again.  Below is what I have for my SQL statements:------------------------------------------------------------------------------------------------------------------------------------- SELECT:SELECT People.FirstName, People.LastName, People.FullName, People.PropertyID, People.InviteTypeID, People.RSVP, People.Wheelchair, Property.[House/Day Hab], InviteType.InviteTypeName FROM (InviteType INNER JOIN (Property INNER JOIN People ON Property.PropertyID = People.PropertyID) ON InviteType.InviteTypeID = People.InviteTypeID) WHERE (People.PersonID = ?)UPDATE:UPDATE [People] SET [FirstName] = ?, [LastName] = ?, [FullName] = ?, [PropertyID] = ?, [InviteTypeID] = ?, [RSVP] = ?, [Wheelchair] = ? WHERE [PersonID] = ? ---------------------------------------------------------------------------------------------------------------------------------------The only fields I want to update are in [People].  My WHERE is based on a control that I use to select a person from a drop down list.  If I run the test query for the update while setting up my data source the query will update the record in the database.  It is when I try to make the update from the gridview that the data is not changed.  If anything is not clear please let me know and I will clarify as much as I can.  This is my first project using ASP and working with databases so I am completely learning as I go.  I took some database courses in college but I have never interacted with them with a web based front end.  Any help will be greatly appreciated.Thank you in advance for any time, help, and/or advice you can give.Brian 

View 5 Replies View Related

Returning Average Of Multiple Rows In A Table Join

Jul 23, 2005

Hi,I'm am looking for a little help. I need to create a SQL view whichjoins a few tables, and I need to return an average for a particularcolumn where a second duplicate ID exists...Heres an example of how the results could be returned...ID | Name | Order No. | Value---+------+-----------+---------5 | test | 1234 | 35 | test2| 1234 | 45 | test3| 1234 | 35 | void | 1235 | 55 | void2| 1235 | 65 | void3| 1235 | 55 | void4| 1235 | 7ID is my main join which joins the tablesName is a unique nameOrder No is the same for the different names, I only need to return onerow with this order no, and the first name (the rest are irrelevant)Value is the field which I wish to return as an average of all 3, 4 orhowever many rows is returned and share the same order no. This iswhere I get totally lost as I am pretty new to SQL. Can anyone provideany help on how I would go about limiting this query to the uniqueorder no's and returning the average of the value field, and I can takeit from there with my own tables.Thanks for your helpstr8

View 3 Replies View Related

SELECT Returning Multiple Values In A Stored Proc

Jul 20, 2005

HiI'm not sure what the best approach for this is:I have a stored procedure which I would like to use to return severaloutput values instead of returning a recordset.CREATE PROCEDURE Test (@param1 int, @param2 int OUTPUT, @param3 intOUTPUT) ASSELECT field2, field3 FROM Table WHERE field1 = @param1I would like to return @param2 as field2 and @param3 as field3How do I do this without using SELECT multiple times?THanks in advanceSam

View 6 Replies View Related

Returning And Reading Multiple Select Statements From One Stored Procedure

Dec 3, 2006

Hey Guys. I’m having a little trouble and was wondering if you could help me out. I’m trying to create a custom paging control, so I create a stored procedure that returns the appropriate records as well as the total amount of records. And that works fine. What I’m having problems with is reading the data from the second select statement within the code. Anyone have any idea on how to do this? Also.. how can I check how many tables were returned?
Here's my code. I'm trying to keep it very generic so I can send it any sql statement:public DataTable connect(string sql)
{
DataTable dt = new DataTable();

SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ToString());
SqlDataAdapter SqlCmd = new SqlDataAdapter(sql, SqlCon);
System.Data.DataSet ds = new System.Data.DataSet();
SqlCmd.Fill(ds);

dt = ds.Tables[0];

//Here's where I don't know how to access the second select statement

return dt;
}  Here's my stored procedure:
 ALTER PROCEDURE dbo.MyStoredProcedure
(
@Page int,
@AmountPerPage int,
@TotalRecords int output
)

AS


WITH MyTable AS
(

Select *, ROW_NUMBER() OVER(ORDER BY ID Desc) as RowNum
From Table
where Deleted <> 1
)


select * from MyTable
WHERE RowNum > (((@Page-1)*@AmountPerPage)) and RowNum < ((@Page*@AmountPerPage)+1);

Select @TotalRecords = COUNT(*)
from Table
where Deleted <> 1
RETURN

Thanks

View 3 Replies View Related

Syntax For Returning And Accessing Multiple Result Sets In MSSQL 2k

Dec 29, 2006

Seasons greetings to everyone,A simple question. Could someone show me the syntax to produce multiple (2 or 3) result sets in a stored proc and how you access those sets from a c# program (ASP.NET)..Couldn't find a reference on Google, maybe I was asking the wrong question! Thanks for any help regardsDavej 

View 3 Replies View Related

Any Help With Returning The Last Instance Of A Multiple Version Record In Joined Tables?

Sep 28, 2007



We have an archive table which keeps each instance of a sales order that was archived under a "Verion No" field. Each time the sales order is archived it is entered into the archive tables (Sales Header Archive, Sales Line Archive). What I am trying to do is write a query to return all sales orders but only the most recent archived version.

For example this table layout is similar to what I am working with. Version No, Order No and Customer No. are the keys between the Header and Line tables, Customer Name column in the output is from only the Sales Header Archive table

SALES LINE ARCHIVE TABLE
Version No - Order No. - Customer No -----> (other columns)
1 s-5 1000

2 s-5 1000
1 s-6 2000

1 s-7 3000
2 s-7 3000
3 s-7 3000
1 s-8 4000
1 s-9 2000
2 s-9 2000


Here is what I need to output to show:

RESULTS OF JOINED TABLES
Version No - Order No - Customer No - Customer Name ---> (other columns)
2 s-5 1000 Something, Inc.
1 s-6 2000 Acme
3 s-7 3000 Company, LLC
1 s-8 4000 Blah & Associates
2 s-9 2000 Acme

It should return the last Version No of each Sales order.

Does that make sense? It is something probably easy... But, I've spent two days using multiples and multiples of different ways, that just aren't working: I'm about to dropkick my server cabinet...

View 4 Replies View Related

SQL Server 2014 :: Select Statement Returning Too Many Rows For Backup Start Date

Jun 3, 2015

Here's my statement below. What I'm trying to get is joining the name column in master.sys.databases with a sub query for the database name, file location and backup start date from the MSDB database. The reason for this, if a new database has never been backed up, It should be returning as a NULL value, which is my goal. However, I'm getting multiple results for the backups.

select CONVERT(CHAR(100), SERVERPROPERTY('Servername')) AS Server,a.name,File_Location=b.physical_device_name,backup_start_date=max(backup_start_date)
from master.sys.databases a
left join(select c.database_name,backup_start_date=max(backup_start_date),b.physical_device_name
from msdb.dbo.backupmediafamily b join msdb.dbo.backupset c on c.media_set_id=c.backup_set_id
where c.type='D'

[Code] .....

View 8 Replies View Related

Current Provider Does Not Support Returning Multiple Recordsets From A Single Execution

Jun 14, 2007

Hi all -



I know this is prolly an old one but I would certainly appreciate some assistance =)



environment:

SERVER (IIS6, .NET2.0, SQL2005)

CLIENT (WIN2000,IE6,VBScript)



I have an aspx that is invoking ado on the clientside. I read somewhere that javascript does not support connecting to SQL clientside. I may be wrong. In any case I am using VBScript on the client.



I am using something like this to invoke the script




Code Snippet

<a href="#" onclick="doReport()">Click Here</< FONT>a>



doReport() looks something like this ...






Code Snippet

' ========================================================

sub doReport()



Dim stSQL, rs, oWord, oDoc, oRng

Dim stCurrentSection, stTemplatePath, dtNow, dtSOR, dtLastDataPoint

Dim iLastDataPoint



set oWord = CreateObject("Word.Application")

stTemplatePath = "http://crivm-ccdev/ccprocharts/supportfiles/CCWordReport.doc"

set oDoc = oWord.Documents.Open(stTemplatePath)

oWord.visible = true









stCurrentSection = "a"



loadDebug

'loadLive







openConnection()

' == THIS DB CALL GETS 2 RESULT SETS

'set rs = getrsCustomerInfoReport(mstUnits, left(mstCycles,3), mstAppName)









set rs = getReadOnlyRS("sCC_GetCustInfo_Report '" & mstUnits & "','" & left(mstCycles,3) & "','" & mstAppName & "'")



' == POPULATE VARS FROM 1st RESULT SET

dtLastDataPoint = rs(0)

iLastDataPoint = rs(1)



set rs = rs.NextRecordset ' <== THIS IS WHERE IS ERROR IS



msgbox rs(0)

end sub









here is my openconnection sub ... oConn is global




Code Snippet

<script type="text/vbscript" language="vbscript">



'== Cursor Location

CONST adUseClient = 3

CONST adUseServer = 2

' == Cursor Type

CONST adOpenStatic = 3

CONST adOpenForwardOnly = 0

CONST adOpenDynamic = 2

' == Lock Type

CONST adLockReadOnly = 1

CONST adLockOptimistic = 3

CONST adLockPessimistic = 2



' ========================================================



sub openConnection()



Dim stConn

set oConn = CreateObject("ADODB.Connection")





'stConn = "DRIVER={sql server};Server=crivm-ccdevsql2005;Database=catcheck;Integrated Security=SSPI"

stConn = "Provider=SQLOLEDB;Server=crivm-ccdevsql2005;Database=catcheck;Integrated Security=SSPI"

'msgbox oConn.state & vbcrlf & stConn1

oConn.open(stConn)

'msgbox oConn.state

ApplySecurity



end sub

' ============================================================

Sub ApplySecurity

'gbhasDBAccess is a global variable on both client and server sides.

'Server side is set in seccheck.asp, which should be at the top of every page

'Client side is set in ApplySecurity() of ConnectServer.asp

Dim appRole



appRole = "appWriters,(tsvc123)"



oConn.Execute "sp_setapprole '" & split(appRole,",")(0) & "','" & split(appRole,",")(1) & "'"



End Sub



</< FONT></script>



Before we moved to SQL2005 I always used this




Code Snippet

' ========================================================

Function getReadOnlyMultRS(strSQL)

set rs = CreateObject("ADODB.Recordset")

rs.CursorLocation = adUseClient

rs.Open strSQL, oConn, adOpenForwardOnly, adLockReadOnly

'Disconnect the Recordset

Set rs.ActiveConnection = Nothing

'Return the Recordset

Set getReadOnlyMultRS = rs

End Function



and this always allowed me to use set rs = rs.nextresultset

but now that we switched to SQL2005 it does not seem to work. I have verified in sql studio that this sp does indeed return 2 resultsets

View 4 Replies View Related

Stored Procedure Returning Multiple Resultsset, Yet Reporting Services Only Uses The First Resultset Returned

Nov 9, 2007

Hi

I have written a stored procedure that returns 8 tables.

When I try to design a server report based on this stored procedure, reporting services only recognises the first table and not the other 7 tables.

I am using SQL Server 2005 and Visual Studio 2005.

Thank you in advance

Jav

View 4 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved