Limiting Result Set From MS SQL Server Query

Jul 23, 2005

Hello,

I am running SQL Server 2000. I would like to know whether
Microsoft Transact-SQL has a method for limiting the result
set from a query in a way analogous to MySQL's LIMIT keyword,
so that, for instance, if the result set contains 10,000 rows,
then only the first 10 rows from the record set are output.

Thank you,

Best Regards,

Neil

View 2 Replies


ADVERTISEMENT

Limiting Result For Pagination

Aug 5, 2004

Hello,

We are migrating from VB6/MySQL to VB6/MS SQL.

The application retrieves limited records for paginated results.
This way we can access large databases, but only return rows for one screen.

For example:
Select row 1 - 10, then 11 - 20 then 21 to 30 etc.

With MySQL we can use LIMIT and OFFSET and it works great.
MySQL
SELECT <columns> FROM <tables> [WHERE <condition>] [ORDER BY <columns>]
[LIMIT [offset,]howmany>]

Does anybody know how we can do something similar with MS SQL?

Any feedback is appreciated!

Thank you,

Edi

View 2 Replies View Related

Limiting Rows Returned By Result Sets

May 20, 2008

In MySQL we use "SELECT (....) LIMIT 0, 10" to only return the first 0 to 10 records. Alternatively we could do "LIMIT 10, 20" to return the 10th to 20th records.

What's the equivilent of this in SQL Server?

Thanks

View 4 Replies View Related

SQL : Limiting Query Question

Aug 18, 2007

 Hello everyone.. I'm working here on a little problem which's driving me nuts : I have two tables :EQUIPMENT :

-EQID
-EQName
-EQblabla QUALITYCHECK :

-QCID
-EQID <---- Is connected with EQUIPMENT
-QCDATE
-QCACTION
-QCnextdate They're needed to manage Qualityactions on some machines we own. Every year, we do quality actions on every machine, after then, we Inserta new QUALITYCHECK-entry into our database and automatically theQCnextdate is generated with QCdate+365days. So far, so easy. So now, how will i do a query against the DB with the NEWEST  QUALITYCHECK-entrys for every machine ? The result has to besmth. like that : EQID | EQName | QCDATE | QCNextdate

1 | machine 1 | 21.12.2006 | 21.12.2007
2 | machine 2 | 21.06.2006 | 21.06.2007
3 | machine 3 | 21.11.2006 | 21.11.2007
4 | machine 4 | 21.12.2005 | 21.12.2006
5 | machine 5 | 23.10.2006 | 23.10.2007

AND NOT

EQID | EQName | QCDATE | QCNextdate

1 | machine 1 | 21.12.2006 | 21.12.2007
1 | machine 1 | 21.12.2005 | 21.12.2006
1 | machine 1 | 21.12.2004 | 21.12.2005
1 | machine 1 | 21.12.2003 | 21.12.2004
2 | machine 2 | 21.06.2006 | 21.06.2007
2 | machine 2 | 21.06.2005 | 21.06.2006
2 | machine 2 | 21.06.2004 | 21.06.2005
2 | machine 2 | 21.06.2003 | 21.06.2004etc..
I tried several things with top 1, subquerys, distinct etc..But unfortunatly it seems that im not capable to solve the problem..I would be thankful for any suggestions !       

View 3 Replies View Related

SQL Query Limiting By Date

Sep 7, 2006

I have a table that looks like

CP | P | ST | Date

where each letter represents a column. I need a SELECT statement that results one row if there is an entry with a date within the last 6 mo for each CP,P,ST combination.

example:

cp1, p1, st1, 1/1/6
cp1, p1, st1, 4/1/6
cp1, p2, st1, 3/1/6

would return just the first and third row...
thanks.

any ideas?

View 2 Replies View Related

Limiting Large Query Results Sets

May 22, 2000

We are trying to limit are query that returns items from our database. The
query currently returns 32,000 records. We are trying to figure out an effecient way so we can request the 1st 50, or the 3rd 50, or the 5th 50 to display to the screen. We dont want to return the entire 32,000 then limit whats displayed to the screen in ADO. We want the select statment to only return 50 at a time. Any suggestions?

View 1 Replies View Related

SQL 2012 :: Limiting Query Results With 3 Criteria For Each Record

Mar 20, 2015

I am trying to write a query that gives me the personal records from speed skaters on e.g. the 500 mtrs. I do this with the query:

SELECT cdsDistance AS Distance
, prsFirstName
, prsLastName
, min(crtFinalTime) AS MinTime
FROM tb....... INNER JOIN etc..
GROUP BY cdsDistance, prsFirstName, prsLastName
ORDER BY min(crtFinalTime)

In itself this works fine. However, there are complicating factors. Sometimes a speed skater has multiple PRs, meaning the he/she has the same fastest time more than once.

If these times are achieved on multple days, the 1st date is the official PR. (meaning: "Min of racedate")
If they are raced on the same day the 1st race is the PR (meaning: "Min of distancenumber")

Changing the code to:

SELECT cdsDistance AS Distance
, prsFirstName
, prsLastName
, MIN(crtFinalTime) AS MinTime
, MIN(cdsStartDate) AS RaceDate
, MIN(cdsDistanceNumber) AS DistanceNumber

FROM tb.......
GROUP BY cdsDistance, prsFirstName, prsLastName
ORDER BY min(crtFinalTime)

This gives me the wrong outcome because it gives me the "MIN" of every field, and they are not necessarily on the same row.

An option would be to calculate min(crtFinalTime), if for a person there is more than 1 result, calculate min of date, and then (if there is still more than 1 row) min of distancenumber.

Seems complicated, and I have the feeling there must be a better way (apart from: how to get this code)

Stacking subqueries in the FROM statement seems like a option be costly (time wise). There are more than 10 million rows (and growing) to run through.

As an example a few times:

DistanceFirst nameLast name Time Date Distance nr.
500 Yuya Oikawa 34.49 201311155
500 Yuya Oikawa 34.49 201311153
500 Yuya Oikawa 34.49 201311172

Yuya has 3 best times (34.49), 15-11-2013 is the 1st date, then distance nr 3 is the 1st distance raced. Therefore the 2nd row is the only row I would like to get in my endresult.

View 4 Replies View Related

Saving Query Result To A File , When View Result Got TLV Error

Feb 13, 2001

HI,
I ran a select * from customers where state ='va', this is the result...

(29 row(s) affected)
The following file has been saved successfully:
C:outputcustomers.rpt 10826 bytes

I choose Query select to a file
then when I tried to open the customer.rpt from the c drive I got this error message. I am not sure why this happend
invalid TLV record

Thanks for your help

Ali

View 1 Replies View Related

End Result Is Main Query Results Ordered By Nested Result

May 1, 2008

As the topic suggests I need the end results to show a list of shows and their dates ordered by date DESC.
Tables I have are structured as follows:

SHOWS
showID
showTitle

SHOWACCESS
showID
remoteID

VIDEOS
videoDate
showID

SQL is as follows:

SELECT shows.showID AS showID, shows.showTitle AS showTitle,
(SELECT MAX(videos.videoFilmDate) AS vidDate FROM videos WHERE videos.showID = shows.showID)
FROM shows, showAccess
WHERE shows.showID = showAccess.showID
AND showAccess.remoteID=21
ORDER BY vidDate DESC;

I had it ordering by showTitle and it worked fine, but I need it to order by vidDate.
Can anyone shed some light on where I am going wrong?

thanks

View 3 Replies View Related

Limiting Size Of A Table In SQL Server

Aug 14, 2004

hi,

im doing network monitoring app where basically i run a checks on servers every few minutes and log the data to a table. Naturally the table can get big, quite quickly. What I want is to be able to overwrite the table data at the start of each new day. Alternatively, rollup the data into a daily or weekly packets and then overwrite table data. How do i do this?

View 1 Replies View Related

SQL Server 2012 :: Query Result For Sequential Range

Aug 9, 2014

I wanted to know the best way to achieve the following results. I have a table that I need output sequential range of vouchers in a table. For instance I have the following data in a column called vouchers. The output will consist of a years worth of vouchers, so voucher numbers may contain gaps and so the need to have a sequential range that has a From and To output. The query needs to know the min and max within that numerical range and then output the next min and max range until it gets to the end.

The data looks like:
ABCD-001869202
ABCD-001869203
ABCD-001869204
ABCD-001869205
ABCD-001869209
ABCD-0018692010
ABCD-0018692011
ABCD-001869309
ABCD-001869310
ABCD-001869311
ABCD-001869312
ABCD-001869313
ABCD-001869314

Desired out put:

From To
ABCD-001869202 ABCD-001869205
ABCD-001869209 ABCD-0018692011
ABCD-001869309 ABCD-001869314

I have tried the following, but it does not quite do what I need it to do, so not sure if I am taking the right approach:

SELECT voucher vouchers,right(voucher, charindex('-', voucher) + 3) voucher
INTO #tempVoucher
FROM LEDGERJOURNALTRANS
where TRANSDATE between '10/1/2013' and '7/31/2014' and VOUCHER like 'APIN%'

[Code] ...

View 6 Replies View Related

SQL Server 2008 :: Limiting To 2 Decimal Points

Aug 31, 2015

The total quantity(sum(woitem.qtytarget) as total) result set is showing more than 6 numbers after the decimal point (example:442.2565485). How can I limit it to 2. (example:442.25)

select wo.num, sysuser.username,sum(woitem.qtytarget) as total
from woitem
join wo
ON wo.id = woitem.woid
Join moitem
on moitem.id = woitem.moitemid
Join mo
ON mo.id = moitem.moid
LEFT JOIN SYSUSER ON mo.userid = sysuser.id
group by sysuser.username, num
ORDER BY CAST( REPLACE( wo.num, ':', '.') as decimal(12, 3))

View 1 Replies View Related

SQL Server 2008 :: How To Result Query With Repeat Sequence Number

Mar 5, 2015

I want to make a query with the result like this, where Seqno is the result query which has repeating sequence number for same Field1

Field1Field2SeqNo
BVFUSBVFUS011
BVFUSBVFUS021
BVFUSBVFUS031
BVFRPBVFRP012
BVFRPBVFRP022

[Code] ....

I want the result also no ordered by Field1. it just as the natural order of the table..

View 3 Replies View Related

SQL Server 2012 :: How To Subtract A Column From A Query Result And Add Difference To Another

Mar 20, 2015

I have a query which provides the below result set:

1165 6
1,173.0013
9740 6
9820 13
2271 6
2287 13
10,952.006
11,029.0013
4,074.006
4,103.0013

I want to achieve something like below. It should subtract the '13' row to '6' row and provide another column with the result. the '6' and '13' category code share the same Key.

1165 6 -8.00
1,173.0013-8.00
9740 6 -80
9820 13 -80

[code]...

View 5 Replies View Related

SQL Server 2014 :: How To Change The Message Text In Management Studio In Query Result

Apr 26, 2014

I have two records...is having pid=10

idpid
10110
10210
1035
1046
1065

then i executed the below query..

update Child set pid=10 where id in (101,102)

the sql server showing message like

(2 row(s) affected) but as per data no records updated so i need to change this message type

if i ran the above update query the the result should be like

(0 row(s) affected)

is there any way to change this...

View 3 Replies View Related

SQL Server 2012 :: Write A Loop On Result Of First Query Inside A Stored Procedure

Jan 23, 2015

I have to write a Stired Procedure with the following functionality.

Write a simple select query say (Select * from tableA) result is

ProdName ProdID
----------------------
ProdA 1
ProdB 2
ProdC 3
ProdD 4

Now with the above result, On every record I have to fire a query Select SUM(sale), SUM(scrap), SUM(Production) from tableB where ProdID= ["ProdID from above query"].How to write this query in a Stored Procedure so that I can get the required SUM columns for all the ProdID's from first query?

View 2 Replies View Related

SQL Server 2012 :: SELECT Query - Cursor To Display Result In Single Transaction

May 25, 2015

Here the SELECT query is fetching the records corresponding to ITEM_DESCRIPTION in 5 separate transactions. How to change the cursor to display the 5 records in at a time in single transactions.

CREATE TABLE #ITEMS (ITEM_ID uniqueidentifier NOT NULL, ITEM_DESCRIPTION VARCHAR(250) NOT NULL)INSERT INTO #ITEMSVALUES(NEWID(), 'This is a wonderful car'),(NEWID(), 'This is a fast bike'),(NEWID(), 'This is a expensive aeroplane'),(NEWID(), 'This is a cheap bicycle'),(NEWID(), 'This is a dream holiday')
---
DECLARE @ITEM_ID uniqueidentifier
DECLARE ITEM_CURSOR CURSOR

[Code] ....

View 1 Replies View Related

SQL Server 2012 :: Select Query - Get Result As Month And Values For All Months Whether Or Not Data Exists

Jul 27, 2015

I have a table with dates and values and other columns. In a proc i need to get the result as Month and the values for all the months whether or not the data exists for the month.

The Similar table would be-

create table testing(
DepDate datetime,
val int)
insert into testing values ('2014-01-10 00:00:00.000', 1)
insert into testing values ('2014-05-19 00:00:00.000', 10)
insert into testing values ('2014-08-15 00:00:00.000', 20)
insert into testing values ('2014-11-20 00:00:00.000', 30)

But in result i want the table as -

Month Value

Jan1
Febnull
Marnull
Aprnull
May10
Junnull
Julnull
Aug20
Sepnull
Octnull
Nov30
Decnull

View 9 Replies View Related

SP To Perform Query Based On Multiple Rows From Another Query's Result Set

Nov 7, 2007

I have two tables .. in one (containing user data, lets call it u).The important fields are:u.userName, u.userID (uniqueidentifier) and u.workgroupID (uniqueidentifier)The second table (w) has fieldsw.delegateID (uniqueidentifier), w.workgroupID (uniqueidentifier) The SP takes the delegateID and I want to gather all the people from table u where any of the workgroupID's for that delegate match in w.  one delegateID may be tied to multiple workgroupID's. I know I can create a temporary table (@wgs) and do a: INSERT INTO @wgs SELECT workgroupID from w WHERE delegateID = @delegateIDthat creates a result set with all the workgroupID's .. this may be one, none or multipleI then want to get all u.userName, u.userID FROM u WHERE u.workgroupIDThis query works on an individual workgroupID (using another temp table, @users to aggregate the results was my thought, so that's included)         INSERT INTO @users             SELECT u.userName,u.userID                 FROM  tableU u                LEFT JOIN tableW w ON w.workgroupID = u.workgroupID                WHERE u.workgroupID = @workGroupIDI'm trying to avoid looping or using a CURSOR for the performance hit (had to kick the development server after one of the cursor attempts yesterday)Essentially what I'm after is:             SELECT u.userName,u.userID
                FROM  tableU u
                LEFT JOIN tableW w ON w.workgroupID = u.workgroupID
                WHERE u.workgroupID = (SELECT workgroupID from w WHERE delegateID = @delegateID) ... but that syntax does not work and I haven't found another work around yet.TIA!    

View 1 Replies View Related

Same Query Gives Result With Different Column Sequence When Used In Query Analyzer

Feb 25, 2012

When I run query in excel it gives result with different column sequence. The same query gives result with different column sequence when used in query analyzer or VBA Macro. E.g., Select * from ABC.

result in Excel 2003 SQL OLE DB query

col-A col-B col-C
values...

Result with Query Analyzer and VBA Macro

col-c col-B col-A
values...

View 3 Replies View Related

Re-display Result Set Without Re-running Query In Query Analyzer?

Apr 9, 2006

I hope I am not asking about something that has been done before, but Ihave searched and cannot find an answer. What I am trying to do is torun a query, and then perform some logic on the rowcount and thenpossibly display the result of the query. I know it can be done withADO, but I need to do it in Query Analyzer. The query looks like this:select Varfrom DBwhere SomeCriteriaif @@Rowcount = 0select 'n/a'else if @@Rowcount = 1select -- this is the part where I need to redisplay the resultfrom the above queryelse if @@Rowcount > 1-- do something elseThe reason that I want to do it without re-running the query is that Iwant to minimize impact on the DB, and the reason that I can't useanother program is that I do not have a develpment environment where Ineed to run the queries. I would select the data into a temp table, butagain, I am concerned about impacting the DB. Any suggestions would begreatly appreciated. I am really hoping there is something as simple as@@resultset, or something to that effect.

View 6 Replies View Related

Transact SQL :: SELECT On Column Name From Query Result Set In Same Query?

May 9, 2015

I have a column colC in a table myTable that has a value (e.g. '0X'). The position of a non-zero character in column colC refers to the ordinal position of another column in the table myTable (in the aforementioned example, colB).

To get a column name (i.e., colA or colB) from table myTable, I can join ("ON cte.pos = cn.ORDINAL_POSITION") to INFORMATION_SCHEMA.COLUMNS for that table catalog, schema and name. But I want to show the value of what is in that column (e.g., 'ABC'), not just the name. Hoping for:

COLUMN_NAME Value
----------- -----
colB        123
colA        XYZ

I've tried dynamic SQL to no success, probably not executing the concept correctly...

Below is what I have:

CREATE TABLE myTable (colA VARCHAR(3), colB VARCHAR(3), colC VARCHAR(3))
INSERT INTO myTable (colA, colB, colC) VALUES ('ABC', '123', '0X')
INSERT INTO myTable (colA, colB, colC) VALUES ('XYZ', '789', 'X0')
;WITH cte AS
(
SELECT CAST(PATINDEX('%[^0]%', colC) AS SMALLINT) pos, STUFF(colC, 1, PATINDEX('%[^0]%', colC), '') colC

[Code] ....

View 4 Replies View Related

Return Result From One Query As A Column In Other Query

Jun 3, 2004

I'm having a bit of a trouble explaining what I'm trying to do here.

I have 3 "source" tables and a "connecting" table that I'm going to use

tblContacts - with contactID, ContactName etc
tblGroups - with GroupID, GroupName
tblSubGroups - with SubGroupID, GroupID and SubGroupName (groupID is the ID for the parent Group from tblGroups)

They are related in a table called
tblContactsGroupConnection - with ContactID, GroupID and SubGroupID

One contact can be related to many subgroups.
What I want is a list of all contacts, with their IDs, names and what groups they are related to:

ContactID, ContactName, [SubGroupName1, SubGroupName2, SubGroupName3]
ContactID, ContactName, [SubGroupName1, SubGroupName3]
ContactID, ContactName, [SubGroupName3]

I'm sure there's a simple solution to this, but I can't find it. Any help appreciated. :)

Kirikiri

View 1 Replies View Related

Save Query Result At CSV Or TXT File From The Query

Dec 10, 2007

We can save query output save as CSV file directly from the Query Analyzer window. I have done it at last few year before. Now I need it.Can anyone please give the one example for the same.

Thanks
Amit K Patel

View 7 Replies View Related

How To Remove Partially Duplicate Rows From Select Query's Result Set (DB Schema Provided And Query Provided).

Jan 28, 2008

Hi, 
Please help me with an SQL Query that fetches all the records from the three tables but a unique record for each forum and topicid with the maximum lastpostdate. I have to bind the result to a GridView.Please provide separate solutions for SqlServer2000/2005. 
I have three tables namely – Forums,Topics and Threads  in SQL Server2000 (scripts for table creation and insertion of test data given at the end). Now, I have formulated a query as below :- 
SELECT ALL f.forumid,t.topicid,t.name,th.author,th.lastpostdate,(select count(threadid) from threads where topicid=t.topicid) as NoOfThreads
FROM
Forums f FULL JOIN Topics t ON f.forumid=t.forumid
FULL JOIN Threads th ON t.topicid=th.topicid
GROUP BY t.topicid,f.forumid,t.name,th.author,th.lastpostdate
ORDER BY t.topicid ASC,th.lastpostdate DESC 
Whose result set is as below:- 




forumid
topicid
name
author
lastpostdate
NoOfThreads

1
1
Java Overall
x@y.com
2008-01-27 14:48:53.000
2

1
1
Java Overall
a@b.com
2008-01-27 14:44:29.000
2

1
2
JSP
NULL
NULL
0

1
3
EJB
NULL
NULL
0

1
4
Swings
p@q.com
2008-01-27 15:12:51.000
1

1
5
AWT
NULL
NULL
0

1
6
Web Services
NULL
NULL
0

1
7
JMS
NULL
NULL
0

1
8
XML,HTML
NULL
NULL
0

1
9
Javascript
NULL
NULL
0

2
10
Oracle
NULL
NULL
0

2
11
Sql Server
NULL
NULL
0

2
12
MySQL
NULL
NULL
0

3
13
CSS
NULL
NULL
0

3
14
FLASH/DHTLML
NULL
NULL
0

4
15
Best Practices
NULL
NULL
0

4
16
Longue
NULL
NULL
0

5
17
General
NULL
NULL
0  
On modifying the query to:- 
SELECT ALL f.forumid,t.topicid,t.name,th.author,th.lastpostdate,(select count(threadid) from threads where topicid=t.topicid) as NoOfThreads
FROM
Forums f FULL JOIN Topics t ON f.forumid=t.forumid
FULL JOIN Threads th ON t.topicid=th.topicid
GROUP BY t.topicid,f.forumid,t.name,th.author,th.lastpostdate
HAVING th.lastpostdate=(select max(lastpostdate)from threads where topicid=t.topicid)
ORDER BY t.topicid ASC,th.lastpostdate DESC 
I get the result set as below:- 




forumid
topicid
name
author
lastpostdate
NoOfThreads

1
1
Java Overall
x@y.com
2008-01-27 14:48:53.000
2

1
4
Swings
p@q.com
2008-01-27 15:12:51.000

I want the result set as follows:- 




forumid
topicid
name
author
lastpostdate
NoOfThreads

1
1
Java Overall
x@y.com
2008-01-27 14:48:53.000
2

1
2
JSP
NULL
NULL
0

1
3
EJB
NULL
NULL
0

1
4
Swings
p@q.com
2008-01-27 15:12:51.000
1

1
5
AWT
NULL
NULL
0

1
6
Web Services
NULL
NULL
0

1
7
JMS
NULL
NULL
0

1
8
XML,HTML
NULL
NULL
0

1
9
Javascript
NULL
NULL
0

2
10
Oracle
NULL
NULL
0

2
11
Sql Server
NULL
NULL
0

2
12
MySQL
NULL
NULL
0

3
13
CSS
NULL
NULL
0

3
14
FLASH/DHTLML
NULL
NULL
0

4
15
Best Practices
NULL
NULL
0

4
16
Longue
NULL
NULL
0

5
17
General
NULL
NULL
0  I want all the rows from the Forums,Topics and Threads table and the row with the maximum date (the last post date of the thread) as shown above. 
The scripts for creating the tables and inserting test data is as follows in an already created database:- 
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK__Topics__forumid__79A81403]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE [dbo].[Topics] DROP CONSTRAINT FK__Topics__forumid__79A81403
GO 
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK__Threads__topicid__7C8480AE]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
ALTER TABLE [dbo].[Threads] DROP CONSTRAINT FK__Threads__topicid__7C8480AE
GO 
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Forums]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Forums]
GO 
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Threads]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Threads]
GO 
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Topics]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Topics]
GO 
CREATE TABLE [dbo].[Forums] (
            [forumid] [int] IDENTITY (1, 1) NOT NULL ,
            [name] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
            [description] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO 
CREATE TABLE [dbo].[Threads] (
            [threadid] [int] IDENTITY (1, 1) NOT NULL ,
            [topicid] [int] NOT NULL ,
            [subject] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
            [replies] [int] NOT NULL ,
            [author] [varchar] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
            [lastpostdate] [datetime] NULL
) ON [PRIMARY]
GO 
CREATE TABLE [dbo].[Topics] (
            [topicid] [int] IDENTITY (1, 1) NOT NULL ,
            [forumid] [int] NULL ,
            [name] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
            [description] [varchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
) ON [PRIMARY]
GO 
ALTER TABLE [dbo].[Forums] ADD
             PRIMARY KEY  CLUSTERED
            (
                        [forumid]
            )  ON [PRIMARY]
GO 
ALTER TABLE [dbo].[Threads] ADD
             PRIMARY KEY  CLUSTERED
            (
                        [threadid]
            )  ON [PRIMARY]
GO 
ALTER TABLE [dbo].[Topics] ADD
             PRIMARY KEY  CLUSTERED
            (
                        [topicid]
            )  ON [PRIMARY]
GO  
ALTER TABLE [dbo].[Threads] ADD
             FOREIGN KEY
            (
                        [topicid]
            ) REFERENCES [dbo].[Topics] (
                        [topicid]
            )
GO 
ALTER TABLE [dbo].[Topics] ADD
             FOREIGN KEY
            (
                        [forumid]
            ) REFERENCES [dbo].[Forums] (
                        [forumid]
            )
GO  
------------------------------------------------------ 
insert into forums(name,description) values('Developers','Developers Forum');
insert into forums(name,description) values('Database','Database Forum');
insert into forums(name,description) values('Desginers','Designers Forum');
insert into forums(name,description) values('Architects','Architects Forum');
insert into forums(name,description) values('General','General Forum'); 
insert into topics(forumid,name,description) values(1,'Java Overall','Topic Java Overall');
insert into topics(forumid,name,description) values(1,'JSP','Topic JSP');
insert into topics(forumid,name,description) values(1,'EJB','Topic Enterprise Java Beans');
insert into topics(forumid,name,description) values(1,'Swings','Topic Swings');
insert into topics(forumid,name,description) values(1,'AWT','Topic AWT');
insert into topics(forumid,name,description) values(1,'Web Services','Topic Web Services');
insert into topics(forumid,name,description) values(1,'JMS','Topic JMS');
insert into topics(forumid,name,description) values(1,'XML,HTML','XML/HTML');
insert into topics(forumid,name,description) values(1,'Javascript','Javascript');
insert into topics(forumid,name,description) values(2,'Oracle','Topic Oracle');
insert into topics(forumid,name,description) values(2,'Sql Server','Sql Server');
insert into topics(forumid,name,description) values(2,'MySQL','Topic MySQL');
insert into topics(forumid,name,description) values(3,'CSS','Topic CSS');
insert into topics(forumid,name,description) values(3,'FLASH/DHTLML','Topic FLASH/DHTLML');
insert into topics(forumid,name,description) values(4,'Best Practices','Best Practices');
insert into topics(forumid,name,description) values(4,'Longue','Longue');
insert into topics(forumid,name,description) values(5,'General','General Discussion'); 
insert into threads(topicid,subject,replies,author,lastpostdate) values (1,'About Java Tutorial',2,'a@b.com','1/27/2008 02:44:29 PM');
insert into threads(topicid,subject,replies,author,lastpostdate) values (1,'Java Basics',0,'x@y.com','1/27/2008 02:48:53 PM');
insert into threads(topicid,subject,replies,author,lastpostdate) values (4,'Swings',0,'p@q.com','1/27/2008 03:12:51 PM');
 

View 7 Replies View Related

Getting Result Of Query Inside Another Query

May 22, 2007

Hi to all,I just need to get two fields from a table and manipulate the resultsin next query of a procedure.I planned to code like what you seebelow,create procedure marks1as@ sql1 as varchar(50)@ sql1=select registerno ,subjectcode from mark;beginselect * from marksetting where registerno='@sql1.registerno' andsubjectcode='@sql1.subjectcode';endcan it be possible to get the results as shown in the code? elsepropose an alternative for this scenario.Thanks in Advance.

View 4 Replies View Related

How To Get Sum() Result In Query?

Mar 15, 2008

mail_delivery_master----------------------ml_id       ml_from_mail_id                          ml_to_mail_id                                ml_user_id      ml_subject                     ml_content             ml_file_attached  ml_no_of_file_attached ----------- ---------------------------------------- -------------- ------------ --------------------------------------------------------------------------------------------------------------------------------1           aa                                       bb                                                cc              dd                             ee                                                                                                                                                                                                                                                                            2           joe@hotmail.com                          tt@gmail.com,                                   JOHNYJP         Forum answer                   somebody answer          0                1                                                                                                                                                                                                                                                                      3           joe@hotmail.com                          mailme@hotmail.com,                             JOHNYJP         Forum answer                   somebody answer          -1               0                                                                                                                                                                                                                                                              4           joe@hotmail.com                          mailme@hotmail.com,janani@ajsquare.net,         JOHNYJP         Forum answer                   somebody answer           0                0                                                                                                                                                                                                                                                             5           joe@hotmail.com                          janani@ajsquare.net,                            JOHNYJP         Forum answer                   somebody answer          0                0                                                                                                                                                                                                                                                               6           joe@hotmail.com                          dff@gg.com,                                     JOHNYJP         Forum answer                   somebody answer           0                0                                                                                                                                                                                                                                                           7           joe@hotmail.com                          tt@gmail.com,janani@ajsquare.net,               JOHNYJP         Forum answer                   somebody answer          0                0                                                                                                                                                                                                                                                             8           Durai@gamial.com                         yogesh@gamail.com                               durai           test                           test                      0                0                                                                                                                                                                                                                                                                9           janani@ajsquare.net                      devi@ajsquare.net                               janu            test                           hi                        0                0                                                                                                                                                                                                                                                             10          janani@ajsquare.net                      devi@ajsquare.net                               JANANI          test                           Miss u                   -1               2                mail_attachementsml_id       ml_file_name                 ml_file_format       ml_file_size      ml_file_select_from                                                                                  ----------- ---------------------------- -------------- ------------ ------------------------------------------ 1           chocolate                       .jpg                         114528            F: empchocolate.pjg                                                                                2           Tiger Caspian Blue.jpg          .jpg                     1114407      F:imageTiger Caspian Blue.jpg                                                                      3           Autumn.jpg                      .jpg                         66287        F:imageAutumn.jpg                                                                                  4           Ascent.jpg                      .jpg                           63244        F:imageAscent.jpg                                                                                  5           Azul.jpg                        .jpg                              61365        F:imageAzul.jpg                                                                                    6           daisy.jpg                       .jpg                             8197         F:imagedaisy.jpg                                                                                   7           Stonehenge.jpg                  .jpg                       59600        F:imageStonehenge.jpg                                                                              i want the result :ml_id , ml_from_mail_id, ml_to_mail_id  from mail_delivery_master   ,,,, and sum(ml_file_size) for that mail from mail_attachements give me the code solution regards samuel chandradoss      

View 2 Replies View Related

Query Result As O/p From SP

Oct 29, 2005

Hi thereI want a stored procedure that contains a Select query. I want SP that return result of query(rows)how could i do this?please help

View 2 Replies View Related

Query Result Help

May 17, 2005

Hi,all,
I ran the two queries and I thought it would be the same, but it's different.
Can you explain to me.

Query 1: result---52 rows
select s.InsuredSurname, s.email from studyUSA s
join interMedical I on s.email=I.email
where convert(char(10), s.enrolldate, 126)>= '2004-01-01'
and convert(char(10), s.enrolldate, 126) <='2005-05-20'
and (s.agentcode not like '162%') and (s.agentcode not like '17%')
and s.agentcode <> '130844'


Query 2: result--14 rows

select s.InsuredSurname, s.email from tis_studyUSA s
where convert(char(10), s.enrolldate, 126)>= '2004-01-01'
and convert(char(10), s.enrolldate, 126) <='2005-05-20'
and s.email IN (Select I.Email from tis_InterMedical I)
and (agentcode not like '162%') and (agentcode not like '17%')
and agentcode <> '130844'

Thanks!
Betty

View 5 Replies View Related

Using Result Of One Query In Another

Sep 29, 2004

hi,

i've tried searching on this but not having much luck, i'm trying to use the result of one and use it in another. is there any way to do this?

So for example, i would use the result of this query and store it in a variable called @tmp_id (if possible)

SELECT TOP 1 ID FROM tblWines WHERE RefNo LIKE 'AB1234';

then use that variable in another query

INSERT INTO tblLogWines (WineID, Date) VALUES (@tmp_id, now());

i've simplied the context to make it a little more understandable, any help is appreciated.

goran.

View 4 Replies View Related

How/what Should Be The Query For This Result

Jun 28, 2006

I have 1 table "Progress"P_no b_no status build_date----------------------------------------------------------------25 1 First_slab 2006/4/525 1 second slab 2006/5/625 2 first slab 2006/1/225 2 third slab 2006/2/3o/p should be asPno,bno, status, max(build_date)sample o/p can be as below25 1 second slab 2006/5/625 2 third slab 2006/2/3Thanks in Advance.

View 4 Replies View Related

Query: How Can I Get This Result?

Jul 20, 2005

Hello all,I tryed to simplify the problem as much as possible. I'll start with theDDL:----------------------------------CREATE TABLE #MyTable(NoID INT,Type CHAR,DateTransaction DATETIME)INSERT INTO #MyTable (NoID, Type, DateTransaction)SELECT 1 AS NoID, 'A' AS Type, '2004-01-01' AS DateTransaction UNION ALLSELECT 2, 'C', '2004-01-01' UNION ALLSELECT 3, 'B', '2004-01-01' UNION ALLSELECT 4, 'C', '2004-01-02' UNION ALLSELECT 5, 'B', '2004-01-02' UNION ALLSELECT 6, 'C', '2004-01-02' UNION ALLSELECT 7, 'A', '2004-01-03' UNION ALLSELECT 8, 'B', '2004-01-03' UNION ALLSELECT 9, 'A', '2004-01-03' UNION ALLSELECT 10, 'C', '2004-01-03' UNION ALLSELECT 11, 'B', '2004-01-03'----------------------------------What I want is all the same Type which, for a same DateTransaction, as adifferent Type inserte beetween them when data is sorted by DateTransactionand NoID. In this case I would like:Type DateTransaction------ -----------------C 2004-01-02 /* B is between two C (NoID = 5) */A 2004-01-03 /* B is between tow A (NoID = 8) */B 2004-01-03 /* A and C are between two B (NoID = 9 and10) */All of these have for the corresponding date at least one transaction with adifferent type between.In the real situation NoID is an autoincrement field, the PK. And theDateTransaction hasn't any time, just a round date.Any suggestion?Thanks for your time.Yannick

View 7 Replies View Related

Need Help With SQL Query And Result Set.

Oct 19, 2007

Good day.

I have a working knowledge of T-SQL but apparently not sufficient to solve my problem.

I have 3 tables defined as:



CREATE TABLE [dbo].[Complaints](

[ComplaintId] [int] IDENTITY(1,1) NOT NULL,

[FileNumber] [varchar](15) COLLATE Latin1_General_CI_AS NOT NULL,

[DateCreated] [smalldatetime] NOT NULL,

[DateReceived] [smalldatetime] NOT NULL,

[Classification] [tinyint] NOT NULL,

[Misconduct] [tinyint] NOT NULL,

[Status] [tinyint] NOT NULL,

[OccurrenceDateTime] [smalldatetime] NOT NULL,

[OccurrenceCityTown] [varchar](50) COLLATE Latin1_General_CI_AS NOT NULL,

[OccurrenceRegion] [tinyint] NOT NULL,

[OccurrenceCountry] [tinyint] NOT NULL,

[CreatorId] [int] NOT NULL,

[CreatedFrom] [tinyint] NOT NULL,

[Flags] [tinyint] NOT NULL,

[Summary] [varchar](8000) COLLATE Latin1_General_CI_AS NOT NULL,

[Comments] [varchar](8000) COLLATE Latin1_General_CI_AS NOT NULL,

CONSTRAINT [PK_Complaints_1] PRIMARY KEY CLUSTERED

(

[FileNumber] ASC

)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]




CREATE TABLE [dbo].[ComplaintSubjects](

[ComplaintSubjectId] [int] IDENTITY(1,1) NOT NULL,

[FileNumber] [varchar](15) COLLATE Latin1_General_CI_AS NOT NULL,

[SubjectId] [int] NOT NULL,

[SubjectType] [tinyint] NOT NULL,

[SubjectIdentity] [tinyint] NOT NULL,

CONSTRAINT [PK_ComplaintSubjects] PRIMARY KEY CLUSTERED

(

[ComplaintSubjectId] ASC

)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]



CREATE TABLE [dbo].[Persons](

[PersonId] [int] IDENTITY(1,1) NOT NULL,

[FirstName] [varchar](32) COLLATE Latin1_General_CI_AS NOT NULL,

[MiddleNames] [varchar](64) COLLATE Latin1_General_CI_AS NULL,

[LastName] [varchar](32) COLLATE Latin1_General_CI_AS NOT NULL,

[AddressNumber] [varchar](10) COLLATE Latin1_General_CI_AS NULL,

[AddressStreet] [varchar](25) COLLATE Latin1_General_CI_AS NOT NULL,

[AddressCity] [varchar](25) COLLATE Latin1_General_CI_AS NOT NULL,

[AddressRegion] [varchar](25) COLLATE Latin1_General_CI_AS NOT NULL,

[AddressCountry] [varchar](25) COLLATE Latin1_General_CI_AS NOT NULL,

[AddressPostalZip] [varchar](20) COLLATE Latin1_General_CI_AS NOT NULL,

[PhoneHome] [varchar](25) COLLATE Latin1_General_CI_AS NULL,

[PhoneWork] [varchar](25) COLLATE Latin1_General_CI_AS NULL,

[PhoneMobile] [varchar](25) COLLATE Latin1_General_CI_AS NULL,

[PhoneFax] [varchar](25) COLLATE Latin1_General_CI_AS NULL,

[DateOfBirth] [smalldatetime] NOT NULL,

[Status] [tinyint] NOT NULL,

[Type] [tinyint] NOT NULL,

[DateAdded] [smalldatetime] NULL,

CONSTRAINT [PK_Personnel_1] PRIMARY KEY CLUSTERED

(

[PersonId] ASC

)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]

) ON [PRIMARY]

Basically, I track complaints and each complaint can have 1 or more subjects associated with it.
The structure is the complaint is referenced in a complaintsubject row and I use the persons table to find out detail of the complaintsubject (firstname, middlename, lastname) complaintsubject just holds Id's to normalize the database rather than have all details of persons table copied into every complaint (pretty basic so far).

My first question is regarding structure...since my complaint to complaintsubject relationship is 1 to many I assume the best way to associate the two is to have a FileNumber field in the complaintsubject linking back to a complaint. Is there any other design that is better suited to this type of relationship?

Second question and most important: I need a way to search by a string that appears in any part of the firstname, middlenames, lastname. I have the query for this and its working. But the problem arises when I have more than one match (i.e. 2 or more people are involved in the complaint where the match string fits both - example say we have a match string of 'an' and in complaint xyz 2 people involved are Sandy Blah and Andy Blue). Now when I do my join to pull out the complaints that involve any people with a name containing 'an' the result set returns the same complaint twice, one for Sandy Blah and the other for Andy Blue). Since I am only interested in certain complaint details and not interested in having the actual people involved returned in the result set, I would like to return only 1 row for each complaint when more than one match is found for the firstname,middlenames,lastname. I could live with having the duplicate rows and process them easily application side, but I am sending a lot of duplicate information over the wire for nothing and would like to optimize this.

I hope I have described this well enough and would greatly, greatly appreciate any help you can provide.

Best Regards.

View 4 Replies View Related







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