问题
What is the role of exec keyword in T-SQL?
I tried
EXEC sp_rename 'mytable.foo', 'bar', 'column';
/* and */
sp_rename 'mytable.foo', 'bar', 'column';
Both commands produced seemingly same result.
回答1:
The EXEC keyword tells SQL that you want to run a stored procedure, function or character string. Syntax can be found here: https://msdn.microsoft.com/en-us/library/ms188332.aspx
EXEC is essential for using transact SQL, when you want to built a SQL statement dynamically. Common practice for this is to build a sql statement in a temporary variable string, then use the EXECUTE keyword to execute it.
i.e.
DECLARE @SQL varchar(MAX)
DECLARE @DynamicColumnName varchar(20)
DECLARE @SomeDatabase varchar(20)
SELECT @DynamicColumnName = 'Column1'
SELECT @SomeDatabase = 'MyDB'
SELECT @SQL = 'USE ' +@SomeDatabase +
' INSERT INTO #NewTable
SELECT '+@DyanmicColumnName +
' FROM Mytable'
EXEC (@SQL)
The above would execute the following statement: 'USE MyDB INSERT INTO #NewTable SELECT Column1 FROM Mytable'
As for GO, it is a command to end a batch of statements. This can be used for a variety of reasons, but I would start your research here: https://msdn.microsoft.com/en-us/library/ms188037.aspx
回答2:
If the EXEC XXX is the first statement in your batch, then using EXEC is optional and you can simply call XXX without using EXEC. But if EXEC is not the first statement in your batch, you SHOULD specify the EXEC in order to call the XXX. However best practice is to use it in any situation as it can increase the readability of your code.
来源:https://stackoverflow.com/questions/37326802/sql-server-exec-keyword