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

edx
edx
92 Points
31 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: 62
Total Answered: 1
Total Marked As Answer: 0
Posted On: 29-May-2021 05:31

Share:   fb twitter linkedin
Answers
beginer
beginer
236 Points
68 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