How To: Retrieve A Value From An Exececuted Query?

Feb 12, 2004

I would like to use a dynamic query to obtain a value...a recordcount specifically.





I have two options so far. The 2nd option works fine, but seems like it would be slower. The first option doesn't recognize that i have declared my variable (@int). Any ideas how i would use the first method...or if it's worth trying?





Method 1





--# produces error: Must declare the variable '@int'.





DECLARE @int as int


EXEC ('SELECT @int = COUNT(ProductID) FROM Products')


print @int








Method2





--# works fine...but seems less efficient.


EXEC ('SELECT ProductID FROM Products')


print @@rowcount

View 4 Replies


ADVERTISEMENT

Query To Retrieve Max Price Without Using Max Function And Sub Query

Mar 5, 2014

ItemIDItemNamePrice

1Item1120.00
2Item2234.00
3Item3250.00
4Item4300.00
5Item5300.00
6Item6290.00
7Item7170.00
8Item890.00
9Item9170.00

the above is the existing table and i need a query to retrieve max price with out using max function and sub query

View 6 Replies View Related

How To Retrieve Id From That Query Line

May 30, 2008

Hey.
I have two sets of tables.
Machine Warranty table (primary key=machine_warranty_id) 
("INSERT into machine_warranty(Job_No, Cust_ID, Machine_SerialNo, Product_ID, Unit_Price, Payment_Type, Date_Installed, Freebies, Remarks, Unit_Location, Date_Paid_MW, Cheque_CC_No, Date_TrialStart, Waterblock, Pressure_Regulator, Rental) VALUES ('" + job + "','" + txt_CustID.Text + "','" + txt_MachineSerialNo.Text + "','" + txt_ProductID.Text + "','" + txt_UnitPrice.Text + "','" + dd_PaymentType.SelectedValue + "','" + txt_DateInstalled.Text + "','" + txt_Freebies.Text + "','" + txt_Remarks.Text + "','" + txt_UnitLocation.Text + "','" + txt_DatePaid_MW.Text + "','" + txt_ChequeCCNo.Text + "','" + txt_DateTrialStart.Text + "','" + dd_WaterBlock.SelectedValue + "','" + dd_PressureRegulator.SelectedValue + "','" + dd_Rental.SelectedValue + "')", connectionOne);
//machine warranty id is a primary key is auto generated already therefore not in the query line.
 
Warranty Period table (primary key=warranty_period_id/ foreign key=machine_warranty_id)("INSERT into warranty_period(Warranty_Period_ID, Warranty_Start) VALUES ('"+ txt_Warranty.Text +"','"+ txt_Warranty_Start.Text +"')", );
 
How to retrieve the machine_warranty_id from the first sql query line? So that I could use it for Warranty Period Insert statement.

View 2 Replies View Related

Query To Retrieve Data From XML

Sep 9, 2014

Here is the sample xml

<ClinicalDocument xmlns:sdtc="urn:h12-org:abcd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:h12-org:v3">
<realmCode code="US" />
<typeId extension="POCD_HD000040" root="2.16.840.1.113883.1.3" />
<templateId root="2.16.840.1.113883.10.20.22.1.1" />
<id root="226ff30f-3b1f-11e3-a969-005056bb0109" />

[code]....

how to write a sql query.

View 2 Replies View Related

SQL Query To Retrieve Result Like This

Aug 24, 2007

I am using SQL Server 2005.

I have a table with records like this:

Date EmpID ADCode ADAmount
----------------------------------------------------------------------
01-Jul-07 101 GPF 150
01-Jul-07 102 GPF.ADV 100
01-Jul-07 103 GPF 250
01-Jul-07 103 GPF.ADV 200
01-jul-07 104 GPF 300

I want to show results like this using a single SQL query:

Date EmpID GPF GPF.ADV
-----------------------------------------------------------
01-Jul-07 101 150 0
01-Jul-07 102 0 100
01-Jul-07 103 250 200
01-Jul-07 104 300 0


I tried:

select PaySlipDate,EmpID,
case ADCode when 'GPF' then ADAmount else 0 end GPF,
case ADCode when 'GPF.ADV' then ADAmount else 0 end 'GPF.ADV'
from EmpSalaryRecord

It is showing like this:

Date EmpID GPF GPF.ADV
-----------------------------------------
01-Jul-07 101 0 0
01-Jul-07 101 150 0
01-Jul-07 102 0 100
01-Jul-07 103 0 0
01-Jul-07 103 250 0
01-Jul-07 103 0 200

It is showing multiple records of each employee for each date. First a record with GPF and GPF.ADV both zero and then records with values. I want a single record for each date and employee.

View 7 Replies View Related

How To Retrieve Only Nth Row As A Result By Writing One Query.

Jan 9, 2006

How to retrieve only nth row as a result of execution of one query?
For example:
Lte the table be:

SNo     SudentName             Marks
001       Ashok kumar               67
002      
Anderson                    
70
003        Alfred  
              
        60
004        Ameeruddin  
              65
005        Kalyan
Kumar.            
69

Now the Query is: How is the 3rd ranker.    The answer must be Ashok kumar.

How to write this query in SQL Server.

View 4 Replies View Related

Query That Join Two Tables And Retrieve A Sum

Jan 13, 2012

I want to join two tables of information together. I want to bring the order information together with the order charge. But since the OrderCharges table can have multiple values, I just want to retrieve the sum of those charges for a specific OrderID+ItemID.

My data looks something like this:

CREATE TABLE #OrderItems
(
OrderItemsID INT IDENTITY (1,1) PRIMARY KEY,
OrderID INT,
ItemID INT
)
SET IDENTITY_INSERT #OrderItems ON

[Code] ....

So I'm looking to see a result set that would like this this:

OrderItemsID-----ItemID-----OrderID----OrderDescription--OrderCharge
----1------------124---------1------------Shipping----------6.55
----2------------156---------1------------Shipping---------16.85
----3------------156---------2------------Shipping----------7.40
----4------------158---------1------------Shipping----------7.85
----5------------158---------2------------Shipping---------15.25

View 2 Replies View Related

Query To Retrieve Unique Records

Jun 7, 2008

I am new to SQL, still learning.

If I want to retreive unique records for e.g. VendorName,City and State however no 2 vendors must be of the same city or state.

How can I do this?

I have used Select and distinct but that still brings unique vendornames in the same state and city. I only need one vendor per city and State.

Help!

View 4 Replies View Related

How Do You Write A Query To Retrieve An Attribute Value From Xml?

Oct 24, 2007



how do you write a query to retrieve an attribute value from xml?
example xml:

<PassportResponse><Passport><RequestID>200409201037256748130032433</RequestID><Status>COMPLETE</Status><CustId>33625</CustId><UserId>00000000000000000000</UserId><RequestTimeStamp>9/20/2004 10:37:25 AM</RequestTimeStamp><CompletedTimeStamp>9/20/2004 10:37:26 AM</CompletedTimeStamp></Passport><Errors /><Reports><Report product="DetailPPC"><ProductCode>LOCNF110</ProductCode><Status>COMPLETE</Status><ReportName>PPC DETAILED NETWORK</ReportName><CriticalResult /><OrderTimeStamp>9/20/2004 10:37:26 AM</OrderTimeStamp><CompletedTimeStamp>9/20/2004 10:37:26 AM</CompletedTimeStamp><RiskAddress /><ADDRESS><ScrubberCode> C1 </ScrubberCode><AddressChanged> Y </AddressChanged><HomeStreetNum>339</HomeStreetNum><HomePreDir /><HomeStreetName>ALL PEAT BEDS</HomeStreetName><HomePostDir /><HomeStreetType>RD</HomeStreetType><HomeCity>EARLTON</HomeCity><HomeState>NY</HomeState><HomeZip>12058</HomeZip><HomeZip4>2707</HomeZip4><HomeCountry>USA</HomeCountry></ADDRESS><PERSONAL><PPC><PRODHEAD><ProductName>PPC</ProductName><PPCErrorCode>L000</PPCErrorCode><PPCErrorMsg>success</PPCErrorMsg><PPCReturnSrc>ADDRESS</PPCReturnSrc><PPCRecordCnt>1</PPCRecordCnt></PRODHEAD><PRODBODY><RECORDNUMBER><PPCVal>7/9 </PPCVal><FireDistrName>COXSACKIE FPD NO 2 </FireDistrName><StateSpecificCode /><FireSubscribeDistrCode /><PPCCountyFIPS>039</PPCCountyFIPS><PPCCountyName>GREENE </PPCCountyName></RECORDNUMBER></PRODBODY></PPC></PERSONAL><COMMERCIAL><PPC><PRODHEAD><ProductName>PPC</ProductName><PPCErrorCode>L000</PPCErrorCode><PPCErrorMsg>success</PPCErrorMsg><PPCReturnSrc>ADDRESS</PPCReturnSrc><PPCRecordCnt>1</PPCRecordCnt></PRODHEAD><PRODBODY><RECORDNUMBER><PPCVal>7/9 </PPCVal><FireDistrName>COXSACKIE FPD NO 2 </FireDistrName><StateSpecificCode /><FireSubscribeDistrCode /><PPCCountyFIPS>039</PPCCountyFIPS><PPCCountyName>GREENE </PPCCountyName></RECORDNUMBER></PRODBODY></PPC></COMMERCIAL></Report></Reports></PassportResponse>'

I want to get back a table of all products. Example
Report product="DetailPPC">

want to return DetailPPC the xml may contain multiple reports I want a table with all the report products:


SELECT PassportResponse.Reports.query('.') as result FROM
@xml.nodes('/PassportResponse/Reports') PassportResponse(reports)


the sql will return the reports but I want to get what the product = only.. I'm hoping to do this without a substring function.

any help would be appreciated.


thanks

View 1 Replies View Related

Transact SQL :: Query To Retrieve Max Count

May 28, 2015

The below is my query in SQL SERVER 2012

DECLARE
@PN_INC INT,
@POSITION_DESC VARCHAR(15)
SELECT @PN_INC= MAX(PositionNumberInc) FROM dbo.tblPosition WHERE LTRIM(RTRIM(UPPER(PositionDescription)))=LTRIM(RTRIM(UPPER(@POSITION_DESC)));
SELECT @PN_INC is returning null when there is no record in the table;

1. how can I make it return 0 when @PN_INC is null else it should pick the MAX(PositionNumberInc) value

2. I have written the below query to return 0 when @PN_INC is null  but I need query to select the MAX(PositionNumberInc) value when @PN_INC is not null 

SELECT @PN_INC= coalesce(MAX(PositionNumberInc), 0) FROM dbo.tblPosition WHERE LTRIM(RTRIM(UPPER(PositionDescription)))=LTRIM(RTRIM(UPPER(@POSITION_DESC)));

View 6 Replies View Related

How To Retrieve Mismatched Records With MS Access Query

Jun 24, 2004

Hi, does anyone know how to retrieve mistmatched records across 2 tables.
To clarify, I have table A with 1175 records and Table B with 894 records.
The records from table A match exactly some the records in table B.

I want to create another table with the extra 281 records from Table A which does not match that of Table B.

I have tried the query with Select where fields_1.a<>fields_2.b AND fields_2.a<>fields_2.b etc
but that doesn't seem to work.

*desparate*

View 2 Replies View Related

Query To Retrieve The Columns That Are Null In A Table

Oct 31, 2006

Hi,

I need help to build a query that shows me how many columns inside a range on columns are null.
Example: quantity1;quantity2;quantity3;quantity4;quantity5; quantity6;quantity7;

Which columns are null?

Thanks in advance

View 6 Replies View Related

Query To Retrieve Records That Sum To A Field In Another Table

May 18, 2012

I really need creating a query that will retreive all records from a table where the dbo.CorpAdv.AcctNum field equals a specific value (for this example "0023"), the TranCode = "R" and the sum of the records, starting with the latest, equals the value of a field in another table (dbo.Master.TotalAdv)

dbo.Master.TotalAdv is numeric (dollar amount) and in this example the value is $1,850.00

dbo.CorpAdv.pID is an integer and unique ID for each record, later records have higher numbers
dbo.CorpAdv.AcctNum is text field
dbo.CorpAdv.AdvAmt is numeric (dollar amounts)

[code]....

View 3 Replies View Related

Query To Retrieve First Names Of Person Where Last Name Is John

Dec 16, 2013

I need a query which retrives the firstnames of the person where last name is john. I am considering the performance as the main factor.

Is there any better query than the following?

Select firstname from tablename where lastname='John'

Considering performance as the major factor....

View 2 Replies View Related

Retrieve All Names That Don't Have A Year (was Query To Be Written To Fetch ....)

Feb 3, 2005

Having two tables.

1. ID Year
----------
1 1990
2 1991
3 1992



2. Name Year
--------------
ABC 1
XYZ 2
123 3


By passing year as an argument, Want to retrieve all the Names that does not have records for that particular year.

For example, if pass 1990, then the result set should be 'XYZ' and '123'

Thanks in advance

View 2 Replies View Related

SQL Server 2008 :: Run Query To Retrieve 650 Unique Records

May 14, 2015

I've a excel spreadsheet with 650 records with unique PONumbers. I need to pull data from SQL server based on the PONumbers. I don't want to run select statement 650 times. How do I retrieve the records in efficient way?

View 9 Replies View Related

SQL Server 2012 :: Retrieve Column From Nested Query

Aug 6, 2015

I have the following query and where I need to use the t_PrevSession.DischargeTime which is in the nested query that is bolded below. How do i bring it up to the main select statement?

SELECT
s.facilityid,
s.sessionid,
s.MRN,

[code]....

View 2 Replies View Related

Linked Server Query To Retrieve Data From Two Different Instances

May 12, 2015

I know how to use Linked server query to retrieve data from two different sql on premise instances.I would like to try the same on sql server instances hosted on azure.When I connect to sql instance, I don't see ServerOBjects->Linked server. I just see Database and security.Is this possible on sql azure, if so how can we achieve it

View 4 Replies View Related

Transact SQL :: Query To Retrieve To What Database A Table Belongs

Jul 16, 2015

I need a query to list the tables in SQL sever with respective database they belong across databases.

I can obtain list of tables from Sys.Tables / Sys.Objects Views but how do I correlate to which DB a table belongs to?

The Sys.Databases View list the  databases with their respective Ids. But, the DBID is not part of Sys.Tables / Sys.Objects Views.

Which View will allow me to fetch database to table mappings? 

View 5 Replies View Related

Sql Query To Retrieve Comments Based On Selected Month And Data

Jan 4, 2008

hi,
i am generating report for my project.
my table goes like
ID   VASID     VASSID     JanMail   JanVisit    JanPhone    JanComment    FebMail   FebVisit    FebPhone   FebComment................. DecPhone  
1      25            4              True         False         False            Mail me             False       True           False            Visit me                  
 
My report has 3 check boxes for Mail,Visit,Phone respectively and a listbox of 12 months january-december respectively.. 
once user check on Mail and select a month suppose January in my report,the report should generate only January Comments.
here user can select any number of months.if user selects january,february and march, report should generate respective months Comments.
Please help me in writing SQL Query to get the comments.......
 
if any one know the solution for the above problem,Please help me
 
Thanks & Regards,
 

View 2 Replies View Related

Using Custom Query To Retrieve And Update Data From Sql Server In SharePoint

Apr 5, 2007

is it possible to make a custom query to fetch and update data from sql server 2005 in SharePoint designer

i make a new data source library and use a custom query to get data but don€™t know how to configure update custom command
can any buddy help me out

View 1 Replies View Related

How To Retrieve Query Results With Now Field Names, Dotted Line Or Footer

Oct 5, 2006

Hi folks,I'm trying to write a simple SELECT statement that will execute inquery analyser but will just have the data with no column names, or thedotted line between them and the data. I also want to avoid thestatement at the end which says nnn rows affected. any ideas? I want todo this because I intend to write the results to a flat file.Thanks for your helpDanny....

View 2 Replies View Related

How To Retrieve The Result From A Stored Procedure That Executes A Dynamically Built Up Sql Query?

Apr 2, 2008

We have a sort of complex user structure in the sense that depending on the type of user the data resides in different tables. Therefor I needed a stored procedure that finds out what table to look for a certain column in. Below is such a stored procedure and it works like it should but my problem is that I don't know how to retrieve the result (which should be a string so can't use RETURN).

I've tried using an OUTPUT variable but since I just run EXEC (@statement) in the end I can't really set an output variable the common way (as in EXEC @outputVariable = PMC_User_GetUserValue(arg1, arg2..)) or can I?

I have also tried to use SELECT to catch the result somehow but no luck and Google didn't help either so now I'm hoping for one of you... Notice that you don't have to bother about much of the code except for the end of it where I want it to return somehow or figure out a way to call this stored procedure and retrieve the result.

Thanks in advance
ripern

-- Retrieves the value of column @columnName for credential id @credID
ALTER PROCEDURE [dbo].[PMC_User_GetUserValue]
@credID int,
@columnName nvarchar(50)
AS

DECLARE @userDataTable nvarchar(50)
DECLARE @userDataID int
DECLARE @statement nvarchar(500)
SET @statement = ' '

SET @userDataID =
(SELECT PMC_UserMapping.fk_userDataID
FROM PMC_UserMapping
INNER JOIN PMC_User ON PMC_UserMapping.fk_user_id = PMC_User.id
WHERE PMC_User.fk_credentials_id = @credID)

SET @userDataTable =
(SELECT PMC_UserType.userDataTable
FROM PMC_UserType
INNER JOIN PMC_UserMapping ON PMC_UserType.id = PMC_UserMapping.fk_usertype_id
INNER JOIN PMC_User ON PMC_UserMapping.fk_user_id = PMC_User.id
WHERE PMC_User.fk_credentials_id = @credID)

SET @statement = 'SELECT ' + @columnName + ' AS columnValue FROM ' + @userDataTable + ' WHERE id=' + convert(nvarchar, @userDataID)

-- Checks whether the given column name exists in the user data table for the given credential id.
IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=@userDataTable AND COLUMN_NAME=@columnName )
BEGIN
EXEC (@statement)
END

View 12 Replies View Related

Reporting Services :: Map Parameter In Report Builder 3.0 Into Query To Retrieve Data From Database

May 29, 2015

Currently, I want to get images of an item in my report for illustration purpose.

Below is my query to get image for item 'GL-10000' in the database. However, I would like to pass a parameter value, '@sItem', from my report so that it would get all related pics of items.  

SQL Query:

Select top 1 item_picture_mst.picture from item_picture_mst
where item_picture_mst.item in (select item_all.item from item_all where item_all.item = 'GL-10000')
ORDER BY item_picture_mst.picture DESC;

View 3 Replies View Related

SQL Select Query Need For Following Criteria. Please Help, Retrieve Records With Independent Price And Its Total Volume Per Min

Jul 17, 2006

Time       Price   Volume
090048       510      6749
090122       510      2101
090135       510      1000
090204       505      2840
090213       505      220
090222       505      1260
090232       505      850
090242       505      200
090253       510      1200
090313       510      570
090343       510      250
090353       510      160
 
Criteria
Retrieve records with independent price and its total volume per minute
 
SELECT SUBSTRING(st,1,4) AS Ttime,d_price AS Price,SUM(l_cum) AS Volume FROM cmd4
WHERE sd='20060717' AND serial='0455'
GROUP BY SUBSTRING(st,1,4),d_price,l_cum
 
Result of the above query: -
Time  Price Volume                 
0900    510     6749
0901    510     1000
0901    510     2101
0902    505     200
0902    505     220
0902    505     850
0902    505    1260
0902    505    2840
0902    510    1200
0903    510    160
0903    510    250
0903    510    570
 
 
THE FOLLOWING RESULT STILL NOT A TOTAL FOR A MINUTE]
E.G
 
0901    510            1000
             +
0901    510            2101
            =         
0901    510            3101 <- I NEED THIS
 
Can any one advice or give me tips over this. Please
 

View 3 Replies View Related

Transact SQL :: Query Fails To Retrieve Full Dataset Using Datetime After Successful Execution Of SSIS Package?

Jun 16, 2015

I have an SSIS Package which Retreives Data using a  SQL Query like below 

select  a.* from dbo.test a (nolock)
JOIN dbo.test1 b (nolock)
ON a.DetailsId = b.DetailsId
JOIN dbo.test c (nolock) on c.DetailsLineId = b.DetailsLineId
where convert(date,c.CpPlacedDate)>?
and convert(date,c.CpPlacedDate)  < convert(date,GETDATE()) 
and c.PartnerCode in ('akakak07')

The CpPlacedDate DataType is Datetime. After the Successfull Execution of SSIS Package the final output results in destination is lesser than source.  

The Maximum of cpplaceddate in the Destination for a particular date is '2015-06-13 23:46:08.923'

The Maximum of cpplaceddate in the Source for a particular date is '2015-06-13 23:59:14.873' 

I am missing 16 records in between this time Gap.

View 3 Replies View Related

SQL Server 2012 :: Sales Over Years - Retrieve Values In Single Query For Multiple Years And Grand Total?

Apr 24, 2015

I need to list customers in a table that represents sales over the years.

I have tables:

Customers -> id | name |...
Orders -> id | idCustomer | date | ...
Products -> id | idOrder | unitprice | quantity | ...

I am using this SQL but it only gets one year:

SELECT customers.name , SUM(unitprice*qt) AS total
FROM Products
INNER JOIN Orders ON Orders.id = Products.idOrder
INNER JOIN Customers ON Customers.id = Orders.idCustomer
WHERE year(date)=2014
GROUP BY customers.name
ORDER BY 2 DESC

I need something like this:

customer | total sales 204 | total sales | 2015 | total sales (2014 + 2015)
--------
customer A | 1000$ | 2000$ | 3000$
customer B | 100$ | 100$ | 200$

Is it possible to retrieve these values in a single SQL query for multiple years and grand total?

View 6 Replies View Related

Retrieve AM Or PM

Aug 10, 2006

HI Chaps

very simple question this time

Is there any method availabe to retrieve AM or PM value from date, IN TSQL

hoping will get answer shortly

regards,

Anas

View 7 Replies View Related

RETRIEVE VALUE AFTER ADD FROM SQLDATASOURCE

Jun 29, 2007

I am using an SQLDataSource to add a product, this works fine, but I would like to know what syntax is used to retrieve the product ID in this case which is return by the SPROC
 
Thanks
 
Steve

View 1 Replies View Related

Retrieve Data

Jan 18, 2008

I need to retrieve points column from my database for the specific user that is signed on and sum all of them. How can I do it using the Gridview and also code in vb for a label? Thanks.  

View 4 Replies View Related

Retrieve Bit Type Value

May 7, 2004

I am trying to populate some controls on a web page with values retrieved from a sql server database recordset. The text type controls work fine. However I have a Check Box on my form. I get a runtime error when I try to write into it. So tried wrting the value into a text control and was suprised to see the value retrieved was "S00817". Heres the relevant line of code

Message.Innerhtml=MyDataset.tables(0).Rows(0)(12)

I would expect this to come up with a 1 or a 0. I get S00817 if the database record holds a 1 or a 0. So what is going on here?

View 2 Replies View Related

Retrieve A Particular Row From A Result Set

Aug 21, 2004

Hi all,

Is it possible to retrieve a particular row from a result set? For eg if my query returns 5 rows and i want to just retrieve the 3rd row from the result....is it possible? If yes...can someone tell me the syntax for it....would appreciate the gr8 help...

Thanks,
SQL Novice

View 1 Replies View Related

How Can I Retrieve Data?

Nov 19, 2005

Here is my sql procedure:
ALTER PROCEDURE dbo.SoftWareShow /* ( @parameter1 int = 5, @parameter2 datatype OUTPUT ) */ @SoftID uniqueidentifierAS SELECT [SoftID], [SoftName], [SoftJoinDate], [SoftSize], [SoftMode], [SoftRoof], [SoftHome], [SoftDemo], [SoftFirstClassID], [SoftSecondClassID], [SoftDesc], [SoftReadCount], [SoftDownCount],ltrim(rtrim([SoftUrlOne])) SoftUrlOne, ltrim(rtrim([SoftUrlTwo])) SoftUrlTwo, ltrim(rtrim([SoftUrlThree])) SoftUrlThree, ltrim(rtrim([SoftUrlFour])) SoftUrlFour FROM [SoftWare] WHERE ([SoftID] = @SoftID) RETURNwhere I retrieve data using sqldatasource, an error appear. how can do ?

View 1 Replies View Related







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