SP Return Multiple Records For A Single Record

May 3, 2007

I have two tables
TermID, Term
1--- Abc
2--- Test
4--- Tunic

and
TermID, RelatedTermID
1 --- 2
1--- 4
2--- 4

I need to get back something like this

TermID, Term, RelatedTermsInformation
1--- test--- test,tunic#1,4


that above was my solution, get the relatedterms information and comma separate, and then put a # and get all the ids comma separate them and then put the in one field. then I can later parse it in the client

this does not seem like a very good solution ( or is it?)
If posible it would be nice to get something like this

TermID, Term, RelatedTermsInformation
1 test RelatedTermsTwoDimentionalArray

but I am not sure how this idea could be implemented using the capabilities of SQL.

my other option is have the client make one call to the database to get the terms and then lots of another calls to get the relatedTerms, but that will mean one trip to the DB for the list term, and one call for every single term found.

any ideas in how to make this better ?

View 8 Replies


ADVERTISEMENT

Return Single Records By Joining Multiple Tables

Jun 4, 2008

I would like to know if it's possible to return a single record by joining the tables below. [Persons]
PersonID [int] | PageViewed [int]
=============== =================
1 10
2 5
3 2
4 12


[PersonNames] - PersonID JOINS Persons.PersonID
PersonID [int] | NameID [int] | PersonName [nvarchar] | PopularVotes [int]
=============== ============== ======================= ===================
1 1 Samantha Brown 5
1 2 Samantha Green 10
2 3 Richard T 10
3 4 Riko T 0
4 5 Sammie H 0


[AltNames] - backup for searches caused by common spelling mistakes
AltNameID [int] | AltNames [nvarchar]
================ =============================
1 Sam, Samantha, Sammie, Sammy
2 Riko, Rico


[PersonAllNames] - JOINS [PersonNames.NameID] ON [AltNames.AltNameID]
NameID [int] | AltNameID [int]
============= ================
1 1
4 1
3 2 
This is ideally what I'd like to have returned: PersonID | PageViewed | MostPopularName | NameSearch
========= ============ ================= =================
1 10 Samantha Green Samantha Brown, Samantha Green, Sam, Samantha, Sammie, Sammy
2 5 Richard T Richard T
3 2 Riko T Riko T, Riko, Rico
4 12 Sammie H Sammie H, Sam, Samantha, Sammie, Sammy
 
 
[MostPopularName] is [PersonNames.PopularVotes DESC].[NameSearch] combines all records from [PersonNames.PersonName] and [AltNames.AltNames].
 
The purpose for this is that I'd like to cache the results table so that all searches can just perform a lookup against the NameSearch field.
Any help would be greatly appreciated.
Thanks, Pete.

View 4 Replies View Related

SQL Server 2012 :: Multiple Records Queried Into Single Record?

Jan 27, 2014

I have 2 tables People and Scores. A person might have 1-5 scores (unknown at time of Query). I would like to query the two tables into a results table and if person does not have a record the score will be zero. Scores also have a test number so you know which score it is. I can get it done with Stored Proc but I have to use Temp tables and then put the temp tables together.

People
Name ID
Tom5
Dick2
Harry3
Larry4
Curly1
Scores
PrimaryKeyPeopleIDScoreTestNumber
12801

[code]....

Results

PrimaryKeyPeopleIdScore1Score2Score3Score4Score5Name
1110090807090Curly
22800000Dick
33909010000Harry
44507090900Larry
559070000Tom

View 8 Replies View Related

Transact SQL :: Use FOR XML To Return Multiple Child Records Within Each Parent Record

Aug 7, 2015

I have a single complex query.

SELECT 
Col1, -- Header, 
Col2, -- Header, 
Col3, -- Detail
Col4, -- Detail 
Col5, -- Detail
FROM 
TableName;

The query repeats the Header row value for all children associated with the header.I need the output of the query in XML format such that..For every Header element in the XML, all its children should come under that header element//I am using - 

SELECT 
Cols 
FROM 
Table Names 
FOR XML PATH ('Header'), root('root') , ELEMENTS XSINIL 

This still repeats the header for each detail (in the XML) , but I need all children for a header under it.I basically want my output in this format - 

<Header >
  <detail 1>
   </detail 1>
  <Detail 2>
  </Detail 2>
  <detail 3>
  </detail 3>
</Header>

View 2 Replies View Related

Results Produce A Single Record Based Off Of Parameters. Want To Change It So It Returns Multiple Records.

Dec 20, 2007

I have a query that will return one record as its results if you provide two variables: @login and @record_date. This works great if you only want one result. However, now what I want to do is not provide those variables and get the result set back for each login and record_date combination. The hitch is that there are several other variables that are built off of the two that are supplied. Here is the query:

DECLARE @login char(20), /*This sets the rep for the query.*/
@record_date datetime, /*This is the date that we want to run this for.*/
@RWPY decimal(18,2), /*This is the required wins per year.*/
@OCPW decimal(18,2), /*This is the opportunities closed per week.*/
@OACW decimal(18,2), /*This is opportunities advanced to close per week.*/
@TOC decimal(18,2), /*This is the total number of opportunities in close.*/
@OANW decimal(18,2), /*This is opportunities advanced to negotiate per week.*/
@TON decimal(18,2), /*This is the total number of opportunities in negotiate.*/
@OADW decimal(18,2), /*This is the opportunities advanced to demonstrate per week*/
@TOD decimal(18,2), /*This is the total number of opportunities in demonstrate.*/
@OAIW decimal(18,2), /*This is the opportunities advanced to interview per week.*/
@TOI decimal(18,2), /*This is the total number of opportunities in interview.*/
@OCW decimal(18,2), /*This is the opportunities created per week.*/
@TOA decimal(18,2) /*This is the total number of opportunities in approach.*/

SET @login = 'GREP'
SET @record_date = '12/18/2007'
SET @RWPY = (SELECT ((SELECT annual_quota FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)/(SELECT target_deal FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)))
SET @OCPW = (SELECT @RWPY/weeks FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)
SET @OACW = (SELECT @OCPW/cls_perc_adv FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)
SET @TOC = (SELECT @OACW*(cls_time/7) FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)
SET @OANW = (SELECT @OACW/neg_perc_adv FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)
SET @TON = (SELECT @OANW*(neg_time/7) FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)
SET @OADW = (SELECT @OANW/dem_perc_adv FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)
SET @TOD = (SELECT @OADW*(dem_time/7) FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)
SET @OAIW = (SELECT @OADW/int_perc_adv FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)
SET @TOI = (SELECT @OAIW*(int_time/7) FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)
SET @OCW = (SELECT @OAIW/app_perc_adv FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)
SET @TOA = (SELECT @OCW*(app_time/7) FROM #pipelinehist WHERE loginname = @login AND record_date = @record_date)

SELECT loginname,
CAST(@TOA AS decimal(18,1)) AS [Opps in Approach],
app_time AS [Approach Average Time],
app_perc_adv AS [Approach Perc Adv],
CAST(@TOI AS decimal(18,1)) AS [Opps in Interview],
int_time AS [Interview Average Time],
int_perc_adv AS [Interview Perc Adv],
CAST(@TOD AS decimal(18,1)) AS [Opps in Demonstrate],
dem_time AS [Demonstrate Average Time],
dem_perc_adv AS [Demonstrate Perc Adv],
CAST(@TON AS decimal(18,1)) AS [Opps in Negotiate],
neg_time AS [Negotiate Average Time],
neg_perc_adv AS [Negotiate Perc Adv],
CAST(@TOC AS decimal(18,1)) AS [Opps In Close],
cls_time AS [Close Average Time],
cls_perc_adv AS [Close Perc Adv]
FROM #pipelinehist
WHERE loginname = @login AND record_date = @record_date

Here is some sample data to use with this. With this sample data what I want to get back is a total of 30 records in the result set each with its data specific to the login and record_date of that returned record.

CREATE TABLE #pipelinehist (
glusftboid int IDENTITY(1,1) NOT NULL,
record_date datetime NOT NULL,
loginname char(20) NOT NULL,
app_new float NOT NULL,
app_time float NOT NULL,
app_perc_adv float NOT NULL,
int_time float NOT NULL,
int_perc_adv float NOT NULL,
dem_time float NOT NULL,
dem_perc_adv float NOT NULL,
neg_time float NOT NULL,
neg_perc_adv float NOT NULL,
cls_time float NOT NULL,
cls_perc_adv float NOT NULL,
target_deal money NOT NULL,
annual_quota money NOT NULL,
weeks int NOT NULL
) ON [PRIMARY]

INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'AREP', 56.8, 26.9, 0.57, 29.5, 0.47, 20, 0.67, 80.7, 0.53, 2.1, 0.97, 2194.93, 575000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'BREP', 33.2, 0.5, 0.9, 7.7, 0.77, 8, 0.77, 9.2, 0.6, 7.7, 0.64, 971.1, 330000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'CREP', 210.2, 0.3, 0.87, 6.6, 0.5, 13.7, 0.4, 16.3, 0.43, 1.5, 0.91, 461.25, 330000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'DREP', 47.6, 5, 0.53, 33.3, 0.6, 57.5, 0.53, 50, 0.7, 1.5, 1, 2045.7, 575000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'EREP', 75.3, 110.9, 0.47, 36, 0.5, 17.4, 0.87, 20.3, 0.6, 7.2, 0.83, 2021.74, 775000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'FREP', 17.2, 23.3, 0.73, 6.8, 0.8, 6.3, 0.93, 29.7, 0.67, 15.5, 0.83, 2218.95, 575000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'GREP', 105.4, 67, 0.2, 32.9, 0.43, 18.5, 0.67, 8.9, 0.77, 3.5, 0.93, 1838.91, 400000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'HREP', 116.4, 118.5, 0.33, 30.9, 0.77, 46.3, 0.77, 46.3, 0.6, 0.9, 0.97, 1735.13, 1150000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'IREP', 143.3, 9, 0.77, 96, 0.17, 21.6, 0.77, 39.9, 0.43, 0.9, 0.93, 1385.43, 400000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'JREP', 179.4, 66.7, 0.7, 67.6, 0.1, 41.4, 0.6, 20.2, 0.8, 14, 0.7, 1563.76, 330000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'KREP', 107.6, 38.2, 0.23, 47.5, 0.47, 21.3, 0.77, 9.6, 0.73, 2.1, 0.83, 2120, 575000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'LREP', 18.6, 8.3, 0.87, 23.2, 0.57, 2.6, 0.87, 12.2, 0.67, 1, 1, 1229.02, 330000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'MREP', 4, 46.2, 0.6, 26.7, 0.57, 8.1, 0.87, 1.7, 0.9, 1.4, 1, 1091.22, 350000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'NREP', 54, 21.6, 0.57, 1.7, 0.77, 11, 0.8, 7.4, 0.9, 49, 0.47, 3240.68, 1300000, 50)
INSERT into #pipelinehist VALUES ('12/17/2007 0:00', 'OREP', 37.6, 24.4, 0.57, 50.1, 0.43, 6.7, 0.87, 15.6, 0.73, 0.9, 0.97, 1163.48, 330000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'AREP', 57.2, 32.5, 0.6, 29.5, 0.47, 20, 0.67, 85.6, 0.5, 2.1, 0.97, 2194.93, 575000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'BREP', 33.9, 0.5, 0.93, 7.8, 0.73, 8.3, 0.77, 9.2, 0.6, 7.7, 0.64, 971.1, 330000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'CREP', 152.1, 0, 0.87, 4.3, 0.67, 9.7, 0.47, 15.7, 0.47, 1.8, 0.85, 396.43, 330000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'DREP', 80.5, 9.8, 0.5, 40.7, 0.57, 68.3, 0.43, 64.2, 0.57, 1.5, 1, 2045.7, 575000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'EREP', 61, 92.1, 0.5, 31, 0.53, 16.9, 0.83, 17.7, 0.6, 7.3, 0.83, 2318.04, 775000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'FREP', 19.4, 21.1, 0.7, 5.3, 0.77, 2.2, 0.93, 33.3, 0.7, 9.7, 0.87, 1937.17, 575000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'GREP', 81.7, 40.5, 0.3, 33, 0.37, 18.5, 0.67, 8.9, 0.77, 3.5, 0.93, 1838.91, 400000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'HREP', 128.6, 115.7, 0.3, 30.9, 0.77, 46.3, 0.77, 48.8, 0.6, 0.9, 0.97, 1728.29, 1150000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'IREP', 100.9, 3.4, 0.77, 86.2, 0.27, 18, 0.8, 54.7, 0.37, 0.9, 0.93, 1385.43, 400000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'JREP', 179.4, 66.7, 0.7, 63.5, 0.1, 41.4, 0.6, 20.2, 0.8, 14, 0.7, 1563.76, 330000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'KREP', 285.2, 36.5, 0.1, 46, 0.43, 24.2, 0.73, 9.6, 0.73, 2.1, 0.83, 2120, 575000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'LREP', 17.6, 7.3, 0.9, 21.5, 0.57, 1.7, 0.87, 12.2, 0.67, 1, 1, 1250.54, 330000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'MREP', 26.7, 46.2, 0.6, 26.7, 0.57, 8.1, 0.87, 1.7, 0.9, 1.3, 1, 979.7, 350000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'NREP', 61.6, 20.8, 0.5, 1.7, 0.77, 11, 0.8, 7.4, 0.9, 49, 0.47, 3240.68, 1300000, 50)
INSERT into #pipelinehist VALUES ('12/18/2007 0:00', 'OREP', 31.6, 16.9, 0.63, 50.1, 0.43, 7.2, 0.87, 19.5, 0.7, 0.9, 0.97, 1303.48, 330000, 50)

View 3 Replies View Related

SQL 2012 :: Query To Make Single Records From Multiple Records Based On Different Fields Of Different Records?

Mar 20, 2014

writing the query for the following, I need to collapse the continuity. If the termdate for an ID is one day less than the effdate of the next id (for the same ID) i need to collapse the records. See below example .....how should i write the query which will give me the desired output. i.e., get min(effdate) and max(termdate) if termdate is one day less than the effdate of next record.

ID effdate termdate
556868 1999-01-01 1999-06-30
556868 1999-07-01 1999-10-31
556869 2002-10-01 2004-01-31
556872 1999-02-01 2000-08-31
556872 2000-11-01 2004-01-31
556872 2004-02-01 2004-02-29

output should be ......

ID effdate termdate
556868 1999-01-01 1999-10-31
556869 2002-10-01 2004-01-31
556872 1999-02-01 2000-08-31
556872 2000-11-01 2004-02-29

View 0 Replies View Related

Return Multiple Rows As A Single Row

Oct 8, 2014

I’m trying to return data in a single row.Here’s what my table looks like:

Employee #,Hours Type,Total Hours
1234,Regular,40
1234,OT,8
1234,Regular,36

[code]....

I need the results of my query to total each hours type and group together:

EmpNo,Sum Of Regular, Sum of Overtime,Sum of Doubletime
1234,76,19,12
7777,45,8,5

I don’t know how to get the data returned in a single row.

View 2 Replies View Related

How To Pull Few Records From A Table (Column) And Concatanate And Return As A Single Value.

Aug 6, 2007



Hi Gurus,
I have a table having sales records and there are more than one record per one customer. The sales table has a reference number like below.














CustomerID
Sales_Ref

2
H_1123

2
H_2344

2
H_4322










I need to do a query and generate the following query.

CustomerID Ref
2 H_1123,H_2344,H_4322

Could someone help me on this.
Thanks.

Cheers,
Vijay

View 3 Replies View Related

Transact SQL :: Pull All Records From One Table And Just A Single Record From Another

Aug 7, 2015

I'm trying to pull all records from one table and just a single record from another.  I have this join, (see below).  It works ok, but the problem is if a blog record doesn't have a corresponding image record it doesn't return.  The end result should be the blog record and a single corresponding image record.  But always a blog record.

SELECT
[Blogs].[ID],
[Blogs].[BlogTitle],
[Blogs].[BlogType],
[Blogs].[BlogText],

[code]...

View 6 Replies View Related

Return Multiple Rows Into One Single String

Nov 1, 2005

Hi,

I need to return multiple rows into one single string

Declare @String varchar(1000)

Create table Cus (CusId Int,CusName varchar(10))

Insert into Cus Select 1,'John'
Union All
Select 2,'Bob'

Select * from Cus returns

1John
2 Bob

I need to return the all the rows from Cus table into a single string. The return is dynamic.
I do not know the number of rows returned

My result should be

@String = 1,John,2,Bob

How can i do that ?

View 2 Replies View Related

How To Return Value From Multiple Rows In A Single String

Oct 7, 2007



I have a table having Style Nos (VarChar Col), how I can return values from multiple rows in a single string.

for Example if table is having 3 records :-

1. Style 1
2. Style 2
3. Style 3

It should return single value in this way

Style 1, Style 2, Style 3


View 10 Replies View Related

How To Return Multiple Columns As Single Column

Mar 9, 2008

I have FirstName,LastName columns in the database.I need to return FirstName,LastName as Name to client(as a single column).

View 3 Replies View Related

Combine Multiple Rows Into Single SQL Record

Jan 28, 2008

Hello:

I have the following table. There are eight section IDs in all. I want to return a single row for each product with the various section results that I have information on.

productID SectionID statusID
10 1 0
10 2 1
10 3 2
10 4 1
10 5 3
10 6 1
11 1 0
11 2 1
11 3 2
11 7 3
11 8 3

Need to return two rows with the respective values for each section.

productID section1 section2 section3 section4 section5 section6 section7 section8
10 0 1 2 1 3 1
11 0 1 2 3 3

Any information or if you can point me in the right direction would be appreciated.

Thanks

View 4 Replies View Related

T-SQL (SS2K8) :: Multiple Databases - Return A Single Table With Three Columns

Jan 13, 2015

I have multiple databases in the server and all my databases have tables: stdVersions, stdChangeLog. The stdVersions table have field called DatabaseVersion which stored the version of the database. The stdChangeLog table have a field called ChangedOn which stored the date of any change made in the database.

I need to write a query/stored procedure/function that will return all the database names, version and the date changed on. The results should look something like this:

DatabaseName DatabaseVersion DateChangedOn
OK5_AAGLASS 5.10.1.2 2015/01/12
OK5_SHOPRITE 5.9.1.6 2015/01/10
OK5_SALDANHA 5.10.1.2 2014/12/23

The results should be ordered by DateChangedOn.

View 4 Replies View Related

Return Value Based On Record With Multiple Types

Jan 15, 2015

I want to return Order records which are one type and don't have the other type.

The issue is I have Orders with which has 2 distriubtion types .

Example
Order 12345 has Type S and Type X.
Order 67891 has Type S

I only want to return Order 67891 that are s Type and does not have type X

View 1 Replies View Related

View Multiple Records In A Single Row?

Jan 3, 2012

Id account num acc_type
42 1376200071278 gl
42 1308111111111 ic
42 1291111111111 os
34 1245200000000 gl
34 1132485111111 ic

this is table structure.there are multiple records like this in a table . I need output as

id gl accountnum ic accountnum osaccountnum
42 1376200071278 1308111111111 1291111111111
34 1245200000000 1132485111111 -

View 7 Replies View Related

Combine Multiple Records Into Single Row

Mar 29, 2007

This is how the data is organized:vID Answer12 Satisfied12 Marketing12 Yes15 Dissatisfied15 Technology15 No32 Strongly Dissatisfied32 Marketing32 YesWhat I need to do is pull a recordset which each vID is a single rowand each of the answers is a different field in the row so it lookssomething like thisvID Answer1 Answer2 Answer312 Saitsfied Marketing Yesetc...I can't quite get my mind wrapped around this one.

View 13 Replies View Related

How We Can Insert Multiple Query With Transaction Roll Bck For A Single Record

Apr 11, 2008

Hello,
I have problem for insert multiple query for insert in differenr tabels for a single record.
I have mail record for candidate and now i wants to insert candiate labour info, candidate passport detail in diff tabel like candidatLabour and candidatePassport,
i used two store procedure for it and i write code for it.and it works fine,but i think that if one SP executed and one record inserted but then some problem occure and 2nd SP not executed then...........
so plz help me
Thanks

View 5 Replies View Related

DTS - Split Single Source Record (text) To Multiple Target (sql)

Aug 31, 2000

I am using DTS and VBScript in DataPump tasks in order to transfer large amounts of data from text files to an SQL database.

As the database uses a normalized schema, there is often the case of inserting multiple records in a destination table from various fields of the same record of the source text file.

For example, if the source record contains information about goods sold like date, customer, item code, item name and total amount, and does so for a maximum of 3 goods per sale (row), therefore has the structure:

[date], [custid], [code1], [name1], [amount1], [code2], [name2], [amount2], [code3], [name3], [amount3]

trying to transfer that record to a [SALES] target table (in a normalized database), we would have to split each source record as follows:

[date], [custid], [code1], [name1], [amount1]
[date], [custid], [code2], [name2], [amount2]
[date], [custid], [code3], [name3], [amount3]

What is the best way to do this using DTS?

I have tried using a datapump task and VBScript, and I guess it has to do with the DTSTransformStat_**** constants, but none of those I used seems to work

Vasilis Siatravanis,
siatravanisv@interamerican.gr , vasilliss@hotmail.com

View 6 Replies View Related

Update Multiple Records From A Single ASP.NET Webpage

Mar 3, 2004

Got a beginner question here...
Let's say I have a database table that houses server information with four columns: make, model, serial #, ip address. And assume there are ten rows with that information filled out. How could I display all the rows of information on a single webpage (ASP.NET), with all the fields being editable; and a single save button that would send any changes to the database (in reality I guess it would be sending all rows and fields to the database, and just overwrite the previous data).

Could a page such as that be created using FrontPage 2003 or Dreamweaver MX 2004?

This would be strictly for updating information. I would have a separate form for adding a new entry.

Thanks for your help.

View 1 Replies View Related

Updating Multiple Records In A Single Table?

Sep 3, 2014

I'm trying to update a checkbox from "False" to "True" within a single table for multiple records. I can update a single record using the script below. However, I'm having trouble applying additional Id's to the string.

(Works) - Update Name_Demo set KEY_CONTACT = 'true' where ID = 225249

(doesn't work) - Update Name_Demo set KEY_CONTACT = 'true' where ID = '225249, 210014, 216543'

It says query executes successfully but returned no rows.

View 3 Replies View Related

Update Multiple Records In Single Transaction

Feb 26, 2008



Hi All,

I want to know that how we will be able to update multiple rows in single transaction.

e.g If original database is
S_No Data
1 -
2 -
3 -
4 -

After
S_No Data
1 1
2 3
3 6
4 10

View 4 Replies View Related

Show Multiple Order Records In Single Row

Mar 13, 2006

I have two tables CompanyTab and OrderTab .CompanyTab table contain one record for each client while OrderTab table contain multiple orders for clients.

I have data in both table like

CompanyTable
ID Name
1 name1
2 name2

OrderTable

OrderId CompanyTabID
1 1
2 1
3 1
4 1

In my query I want to show all orders in single row.

ID Name Orders
1 name1 1,2,3,4
2 name2 null

Is anybody can help on it.

Thanks
Arvind

View 5 Replies View Related

Sql Query To Return Multiple Records

Nov 9, 2006

Hi,

I'm trying to retrieve some records from an SQL database.


I've a table named CustomerOrder with three fields - custID , productname and quantity


No keys in the table. it's row based approach. every custID can have multiple entries for different products.

Example:

CustID ProductName Quantity
1 Product1 2

1 Product2 3

2 XXX 1

2 Product1 2

1 Product3 4

I would like to write a query that gives the result as follows :

CustID ProductName Quantity
1 Product3 4

2 Product1 2

Meaning that, query has to retrieve only one record per custID based on highest quantity.


select custId,Productname,quantity from customerorder where quantity = (select max(quantity) from customerorder)

the above query returns only one record. (ofcourse..)

Kindly help me to get the desired.

Thank You.

View 5 Replies View Related

Generate Single Record That Shows Status Of Accounting Period For Multiple Groups?

Mar 26, 2015

I'm trying to generate a single record that shows the status of an accounting period for multiple groups. For a single accounting period they could all be the same, or all be different (open, closed, hold, etc)

What I want to do is select the accounting period with a group by that says if all the groups are in the same status, then that's the status. But if there are different status' for the period, I just want to have a single line that says 'Mixed' The query below returns 3 records, but I only want 2. I tried a CASE WHEN Having COUNT > 1 but it blew up with an aggregate subquery in a group by error.

DECLARE @AccountingPeriod Table
(AccountingPeriod varchar(10), Status char(1), GroupNum int)
Insert into @AccountingPeriod
Values('2015-03','O',1),
('2015-03','O',2),
('2015-03','O',3),
('2015-02','O',1),
('2015-02','O',2),
('2015-02','C',3)
Select AccountingPeriod, Status from @AccountingPeriod
GROUP BY AccountingPeriod, Status

View 3 Replies View Related

Update Multiple Varbinary Records With Single Sql Statement

Jan 16, 2007

I am renovating an existing application and am converting the existing passwords into hashed values using SHA1. I know how to compute the hashed values as a byte array for each record. What I don't know how to do easily is update all of the records i a single call to the database. Normally, I would just do the following:UPDATE HashedPassword = someValue WHERE UserID = 101;
UPDATE HashedPassword = someOtherValue WHERE UserID = 102;
...

What I don't know is what someValue and someOtherValue should be. How do I convert my byte array into string representation that SQL will accept? I usually execute multiple statements using Dim oCmd as New SqlCommand(sSQL, MyConn) and then call oCmd.ExecuteNonQuery().
Alternatively, I found the following code that uses the byte array directly but only shows a single statement. How could I use it to execute multiple statements as shown above?'FROM http://aspnet.4guysfromrolla.com/articles/103002-1.2.aspx

'2. Create a command object for the query
Dim strSQL as String = _
"INSERT INTO UserAccount(Username,Password) " & _
"VALUES(@Username, @Password)"
Dim objCmd as New SqlCommand(strSQL, objConn)

'3. Create parameters
Dim paramUsername as SqlParameter
paramUsername = New SqlParameter("@Username", SqlDbType.VarChar, 25)
paramUsername.Value = txtUsername.Text
objCmd.Parameters.Add(paramUsername)

Dim paramPwd as SqlParameter
paramPwd = New SqlParameter("@Password", SqlDbType.Binary, 16)
paramPwd.Value = hashedBytes
objCmd.Parameters.Add(paramPwd)

'Insert the records into the database
objConn.Open()
objCmd.ExecuteNonQuery()
objConn.Close()
 

View 1 Replies View Related

Insert Multiple Records Into A Single Field On Another Table

Feb 15, 2012

I have a table JOBCODE which contains a list of codes.

I want to insert these values into table VIEWS as a list separated by spaces.

E.G.

Table Jobcodes looks like this

code
1
2
3
4
5
6

And I want table Views to look like this:

field1
1 2 3 4 5 6

How do I go about this?

View 4 Replies View Related

T-SQL (SS2K8) :: Inserting Multiple Records From A Single Variable?

Apr 24, 2014

I have two tables. Table 1 has column "job", table 2 has column "job" and column "item". In table table 2 there are multiple "items" for each "job"

I would like to insert all of the "items" into table 1, based on a join table1.job = table2.job

View 7 Replies View Related

Displaying Multiple Records From One Record

Jan 26, 2007

Hi there,
I've a complex stored procedure, which I'm trying to get a list of one or more users based the list of records that are being display.  If I mentioned the overall store procedure here it'll turn you off, so I'll put the questions in bitesize chunks.
Example would be if Bob and Luke work for Acrm Corp and John for Maxwellarms Ltd, and there was an intimediate table which linked both.  With my stored procedure I want to display both names in the same row as Acrm Corp.  Is there a way to do this? 
User tableUserid      Username
1             Bob2             Luke3             John
Store procedure resultCompanyname         Username
Acrm Corp               NullMaxwellarm Ltd        Null
Regards,

View 1 Replies View Related

Combining Multiple Records Into One Record

Dec 20, 2007

Hi All,

I'm trying to develop a query that joins one record from a table with multiple matching records from another table all in one record,
Table1 has the primary key
id
--
1
2
3
4
Table2 has the follwing records
id year subject
-----------------
1 2000 English
1 2002 French
2 2004 English
2 2005 English
2 2006 English
3 2007 French
I want the result to be like this
id 2000 2001 2002 2003 2004 2005 2006 2007
-----------------------------------------------------------
1 English null French null null null null null
2 null null null null English English English null
3 null null null null null null null English

Appretiate your assistance

View 4 Replies View Related

How To Combine Multiple Rows Data Into Single Record Or String Based On A Common Field.

Nov 18, 2007

Hellow Folks.
Here is the Original Data in my single SQL 2005 Table:
Department:                                            Sells:
1                                                              Meat
1                                                              Rice
1                                                              Orange
2                                                              Orange
2                                                              Apple
3                                                             Pears
The Data I would like read separated by Semi-colon:
Department:                                            Sells:
1                                                             Meat;Rice;Orange
2                                                             Orange;Apple
3                                                             Pears
I would like to read my data via SP or VStudio 2005 Page . Any help will be appreciated. Thanks..
 
 

View 2 Replies View Related

Transact SQL :: Stored Procedure To Return Multiple Records

Oct 21, 2015

I am looking out for sample  stored procedures returning multiple records

Example: GetOrderDetailsByOrderId

The above stored procedure should take orderId as parameter and should return the the order details along mutiple line item details.

View 4 Replies View Related

Insert Multiple Records - First Record Is Insterted Twice: Why?

May 5, 2008

Hi and thanks for any advice.Right now I have a for loop that  inserts multiple records.  The first record is inserted into the database and I am not sure why.  Here is the code I am using -   Dim intPhotoKeyID As Integer
Dim InsertCmd As String = "Insert into Photos (OriginalName, GalleryID, PhotoDesc "
InsertCmd += ") values " & _
"(@OriginalName, @GalleryID, @PhotoDesc " & _
") "
InsertCmd += "; SELECT CAST(scope_identity() AS int);"

Dim DBConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("SqlConnGalleries").ConnectionString)
Dim MyCommand = New SqlCommand(InsertCmd, DBConnection)
MyCommand.Connection.Open()
MyCommand.Parameters.Add(New SqlParameter("@OriginalName", SqlDbType.VarChar, 150))
MyCommand.Parameters.Add(New SqlParameter("@GalleryID", SqlDbType.Int))
MyCommand.Parameters.Add(New SqlParameter("@PhotoDesc", SqlDbType.Text))
myCount = myCount & i 'Is zero for first two records
MyCommand.Parameters("@OriginalName").Value = "Orig" & i
MyCommand.Parameters("@GalleryID").Value = 5

MyCommand.Parameters("@PhotoDesc").Value = MyCommand.CommandText & myCount

Try
intPhotoKeyID = Convert.ToInt32(MyCommand.ExecuteScalar())
MyCommand.Connection.Close()
Catch Exp As Exception
Response.Write(Exp)
'ResultsLabel.Text = Exp.ToString()
End Try
DBConnection.Close()  Below is the whole procedure which either uploads an image or directory of images and resizes them. Then gets the meta data from the image. Then creates an entry into the database for each image. If I am dealing with 4 images then 4 images are uploaded to the new gallery folder. But 5 entries are added to the database. Thanks again for any help, Jennifer  Protected Sub Upload(ByVal sender As Object, ByVal e As EventArgs)


If ListDirectories.SelectedValue.Length > 0 Or fileUpEx.HasFile Then
Dim i As Integer
Dim selectedDirectory As String = ListDirectories.SelectedValue
Dim photoDescription As String
Dim photoAuthor As String
Dim photoTitle As String = ""
Dim photoName As String
Dim myFiles As String()
Dim fileCount As Integer

If multiUpload.Visible = True Then
myFiles = Directory.GetFiles(Server.MapPath(".") & "/tempimages/" & ListDirectories.SelectedValue & "/")
fileCount = myFiles.Length - 1
Else
fileCount = 0
End If

'Get last photo order from Photo table
Dim PhotoMaxOrder As Integer = 0
Dim DS As DataSet ' DataSet object
Dim SQL As String = "SELECT MAX(PhotoOrder) FROM Photos WHERE GalleryID=" & Request("ID").Trim
Dim connString As String = ConfigurationManager.ConnectionStrings("SqlConnGalleries").ConnectionString
Dim sqlDA = New SqlDataAdapter(SQL, connString)
DS = New DataSet
sqlDA.Fill(DS, "Photos")
If Not DS.Tables("Photos").Rows(0).Item(0) Is System.DBNull.Value Then
If DS.Tables("Photos").Rows.Count > 0 Then
PhotoMaxOrder = Convert.ToInt32(DS.Tables("Photos").Rows(0).Item(0)) + 1
End If
Else
PhotoMaxOrder = 1
End If

For i = 0 To fileCount

If multiUpload.Visible = True Then
photoName = Right(myFiles(i), InStr(StrReverse(myFiles(i)), "/") - 1)
Else
photoName = fileUpEx.PostedFile.FileName
End If

If InStr(photoName, ".jpg") > 0 Then
Dim MyPhoto As Bitmap

If multiUpload.Visible = True Then
MyPhoto = New Bitmap(myFiles(i))
Else
MyPhoto = Bitmap.FromStream(fileUpEx.PostedFile.InputStream)
End If
'testFile = myFiles(i)
Try 'Get photo description
Dim Make As PropertyItem = MyPhoto.GetPropertyItem("270")
Dim ascii As Encoding = Encoding.ASCII
photoDescription = ascii.GetString(Make.Value, 0, Make.Len - 1)
Catch ex As Exception
photoDescription = ""
End Try

Try 'Get photo author
Dim Make As PropertyItem = MyPhoto.GetPropertyItem("315")
Dim ascii As Encoding = Encoding.ASCII
photoAuthor = ascii.GetString(Make.Value, 0, Make.Len - 1)
Catch ex As Exception
photoAuthor = ""
End Try

Dim photoXmpData As String = GetXmpXmlDocFromImageStream(MyPhoto)

If Not photoXmpData = "" Then
photoTitle = GetXmpXmlNode(photoXmpData)
End If

'insert photo record into photo table






Dim intPhotoKeyID As Integer
Dim InsertCmd As String = "Insert into Photos (OriginalName, GalleryID, PhotoDesc "
InsertCmd += ") values " & _
"(@OriginalName, @GalleryID, @PhotoDesc " & _
") "
InsertCmd += "; SELECT CAST(scope_identity() AS int);"

Dim DBConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("SqlConnGalleries").ConnectionString)
Dim MyCommand = New SqlCommand(InsertCmd, DBConnection)
MyCommand.Connection.Open()
MyCommand.Parameters.Add(New SqlParameter("@OriginalName", SqlDbType.VarChar, 150))
MyCommand.Parameters.Add(New SqlParameter("@GalleryID", SqlDbType.Int))
MyCommand.Parameters.Add(New SqlParameter("@PhotoDesc", SqlDbType.Text))
myCount = myCount & i 'Is zero for first two records
MyCommand.Parameters("@OriginalName").Value = "Orig" & i
MyCommand.Parameters("@GalleryID").Value = 5

MyCommand.Parameters("@PhotoDesc").Value = MyCommand.CommandText & myCount

Try
intPhotoKeyID = Convert.ToInt32(MyCommand.ExecuteScalar())
MyCommand.Connection.Close()
Catch Exp As Exception
Response.Write(Exp)
'ResultsLabel.Text = Exp.ToString()
End Try
DBConnection.Close()

'check photo width and height
Dim NewFilePath As String = Server.MapPath("/appscode/galleries/photos/g" & Request("ID").Trim & "/") & "p" & intPhotoKeyID.ToString & ".jpg" ' & photoName
lblMessage2.Text = lblMessage2.Text & InsertCmd
If MyPhoto.Width.ToString = "200" Or MyPhoto.Height.ToString = "200" Then
'just copy the image
If multiUpload.Visible = True Then
File.Copy(myFiles(i), NewFilePath, True)
Else
fileUpEx.SaveAs(NewFilePath)
End If
Else
'resize image
Dim NewSize As System.Drawing.Size = New System.Drawing.Size(200, 200)
ResizePicture(MyPhoto, NewFilePath, NewSize) 'and save it
End If
MyPhoto.Dispose()
GC.Collect()
End If

Next
If Not myFiles Is Nothing Then
If myFiles.Length > 0 And multiUpload.Visible = True Then
'delete directory that was just processed
Directory.SetCurrentDirectory(Server.MapPath("."))
Directory.Delete(Server.MapPath(".") & "/tempimages/" & ListDirectories.SelectedValue & "/", True)
ListDirectories.Items.Remove(selectedDirectory)
'lblMessage2.Text = "Your file(s) have been added."
End If
Else
'lblMessage3.Text = "Your file has been added."
End If

Else
lblMessage2.Text = "Please select a folder."
End If

lblMessage3.Text = myCount
End Sub     

View 8 Replies View Related







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