How to pass dynamic SELECT TOP @var In SQL Server?

edx
edx
506 Points
24 Posts

How can I put a dynamic variable for getting number of rows to return in SQL Server? Below is not valid syntax in SQL Server :

DECLARE @TopCount int
SET @TopCount = 20

SELECT TOP @TopCount * FROM SomeTable
Views: 1446
Total Answered: 1
Total Marked As Answer: 0
Posted On: 29-May-2021 05:31

Share:   fb twitter linkedin
Answers
beginer
beginer
1544 Points
52 Posts
         

You are doing well. Just need to add small brackets as:

DECLARE @TopCount int
SET @TopCount = 20

SELECT TOP (@TopCount) * FROM SomeTable
Posted On: 04-Jun-2021 21:58
 Log In to Chat