tags:

views:

435

answers:

7

Hi all.

I want to select at least 20 records from a table into a new table based on a number 1 to 20.

select * into blah from foo where fubar = '1'

how do i add 1 to 20 into that statement?

edit:

select * into blah from foo where fubar = '1' and where fubar = '2' and where fubar = '3'

Sorry. Let me see if i can make it more clear. Basically i want to select 20 record based on fubar = 1 to 20. I tried to use "and where" but i get a syntax error.

eidt: what if fubar is nvarchar(11)

A: 
selet top 20 * into blah from foo where fubar = '1'

I'm not really sure what you're asking though.

EDIT:

selet top 20 * into blah from foo where fubar IN ('1','2',...'20')
roman m
A: 

You looking at just inserting the top 20 records?

SELECT TOP 20 *
INTO
    blah
FROM
    foo
WHERE
    fubar = '1'

There are also many ways that you can parameterize the TOP clause too (the examples are for SQL Server).

EDIT:

In response to your update, if fubar column is numeric, then it's simply

SELECT * INTO blah FROM foo WHERE fubar BETWEEN 1 AND 20

if fubar is a character field but contains only numbers then you can cast the field to Integer and still use the BETWEEN clause

SELECT * INTO blah FROM foo WHERE CAST(fubar AS INT) BETWEEN 1 AND 20

This is for SQL Server

Russ Cam
+2  A: 
TStamper
updated with the second one..either one works
TStamper
+1 for having the same answer as me and not knowing who posted it first.
gpojd
+1  A: 

Two cheesy methods both involving changing the where clause:

If fubar is a numeric column try where fubar >0 and fubar < 20 if fubar is a character column try where fubar in ('1','2','3', ... '19','20')

I am sure there are more effective methods that are general but this might help you out in a particular circumstance.

ojblass
I think your cheesy methods is what i'm looking for. Thank. I'm hold off to see if someone can afford a better statement.
Jack
A: 

It depends on database you are using. For MS SQL Server it will be

SELECT TOP 20 * into blah from foo order by fubar

For Oracle

SELECT * into blah from foo  order by fubar where rownum()<=20
Dmitry Khalatov
+5  A: 
SELECT * INTO blah FROM foo WHERE fubar BETWEEN 1 AND 20
gpojd
I am so mad you got votes for the answer I put first :( ...j/k
TStamper
this won't work for nvarchar fields
roman m
@rm: The OP said "based on a number 1 to 20", so I think this should work for him.
gpojd
@tstamper: I didn't see anyone else with this answer when I posted, I don't know who posted first, but if it was you, I will certainly upvote you and give you credit. Right now, it says "answered 2 hours ago" for both of us.
gpojd
@gpojd-- just making it a sport..nothing serious..having fun with it
TStamper
A: 

Change your 'AND" to an 'OR':

select * into blah 
from foo 
where fubar = 1 
OR fubar = 2 
OR fubar = 3
John Dibling