Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select TOP x From table

Tags:

sql

select

This is a rather unique problem and I don;t know if there is an answer. Im trying to input a variable amount of records to insert into a table depending on the value of another table. This is what I have tried

insert into TABLE1
select TOP cast((select Value from TABLE3 WHERE column_name = 'blah') as int) * from TABLE2 

So im trying to get the value from table 3, and use that value to grab the top x records from table 2 to be inserted into table 1.

the error listed is Incorrect syntax near cast.

like image 570
DidIReallyWriteThat Avatar asked Nov 07 '25 11:11

DidIReallyWriteThat


2 Answers

OP doesn't specify the database they are using, but SQL Server allows a variable. try it out:

declare @YourTable table (RowID int identity(1,1), ColA char(4))
INSERT INTO @YourTable values ('a');INSERT INTO @YourTable values ('aa');INSERT INTO @YourTable values ('aaa');
INSERT INTO @YourTable values ('b');INSERT INTO @YourTable values ('bb');INSERT INTO @YourTable values ('bbb');
INSERT INTO @YourTable values ('c');INSERT INTO @YourTable values ('cc');INSERT INTO @YourTable values ('ccc');

declare @x int=5
select top (@x) * from @YourTable

output:

      RowID ColA
----------- ----
          1 a   
          2 aa  
          3 aaa 
          4 b   
          5 bb  

(5 row(s) affected)
like image 79
KM. Avatar answered Nov 10 '25 00:11

KM.


TOP x cannot be specified in a variable.It actually can, see KM's answer (which is definitely better than mine).

An option here would be a dynamic query

DECLARE @topx AS integer;
SET @topx = (select Value from TABLE3 WHERE column_name = 'blah')

DECLARE @query AS varchar(max);
SET @query = 'INSERT INTO table1 SELECT TOP ' + convert(varchar(10),@topx) 
              + ' FROM table2'

exec sp_executesql query
like image 37
Tomas Pastircak Avatar answered Nov 10 '25 01:11

Tomas Pastircak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!