TOP words related issues plus SQL variables

After the SQL Server database variables can be loaded TOP clause, the following questions will be added to SQL TOP clause variables are discussed, for your reference, hoping to help you learn SQL database.

SQL Server2005 started after TOP clause with constant or variable time constant may be omitted with parenthesis, i.e. top (2) and the top 2 are equivalent (note without brackets when the top and two spaces), using the top parentheses SQL variables must be, for example: 
the Sql Code
DECLARE @num int   
SET = 10 @num    
SELECT Top (@num) * from SYS.TABLES  

declare @num int
set @num = 10
select top(@num) * from sys.tables

Using dynamic SQL for: 
the Sql Code
DECLARE @num int   
SET = 10 @num    
DECLARE @str nvarchar (1000)    

set @str = 'select top('+cast(@num as nvarchar(10))+') * from sys.tables'   
exec(@str)  

declare @num int
set @num = 10
declare @str nvarchar(1000)
set @str = 'select top('+cast(@num as nvarchar(10))+') * from sys.tables'
exec(@str)

Some remarks on the exec: 
1. When the exec command parentheses character only comprise one variable or a text string, or a string variable in series with the string of text. Can not be used in parentheses CASE expression or function, it is preferable to code in a variable, then the SQL exec command variable as a parameter 
2.exec (<string>) do not provide an interface and therefore can not access the dynamic batch local variables defined in the calling batch must be connected in series into a string variable content, just like the example above. If the above example of a dynamic SQL code is written as Sql
SET @str = 'SELECT Top (' + @ + NUM ') from SYS.TABLES *';    
Exec (@str)  

@str = SET 'SELECT Top (' + @ + NUM ') from SYS.TABLES *';
exec (@str)
will be given 
3. exec not support the same output parameters, if we want to enter into a SQL variable , insert must first enter a target table, and then assigns the value of the variable from the target table Example


Reproduced in: https: //www.cnblogs.com/kevinGao/p/3702267.html

Guess you like

Origin blog.csdn.net/weixin_34223655/article/details/93052025