create proc test @TableName varchar(50) AS exec ('SELECT * FROM '+@TableName) GO
使用带一个变量的 EXECUTE 'tsql_string' 语句 这个例子显示 EXECUTE 语句如何处理动态生成的、含有变量的字符串。这个例子创建 tables_cursor 游标来保存所有用户定义表 (type = U) 的列表。说明 此例子只用作举例。 DECLARE tables_cursor CURSOR FOR SELECT name FROM sysobjects WHERE type = 'U' OPEN tables_cursor DECLARE @tablename sysname FETCH NEXT FROM tables_cursor INTO @tablename WHILE (@@FETCH_STATUS <> -1) BEGIN /* A @@FETCH_STATUS of -2 means that the row has been deleted. There is no need to test for this because this loop drops all user-defined tables. */. EXEC ('DROP TABLE ' + @tablename) FETCH NEXT FROM tables_cursor INTO @tablename END PRINT 'All user-defined tables have been dropped from the database.' DEALLOCATE tables_cursor
create proc test @TableName as varchar(50) AS exec ('SELECT * FROM '+@TableName) GO
AS
exec ('SELECT * FROM '+@TableName)
GO
这个例子显示 EXECUTE 语句如何处理动态生成的、含有变量的字符串。这个例子创建 tables_cursor 游标来保存所有用户定义表 (type = U) 的列表。说明 此例子只用作举例。
DECLARE tables_cursor CURSOR
FOR
SELECT name FROM sysobjects WHERE type = 'U'
OPEN tables_cursor
DECLARE @tablename sysname
FETCH NEXT FROM tables_cursor INTO @tablename
WHILE (@@FETCH_STATUS <> -1)
BEGIN
/* A @@FETCH_STATUS of -2 means that the row has been deleted.
There is no need to test for this because this loop drops all
user-defined tables. */.
EXEC ('DROP TABLE ' + @tablename)
FETCH NEXT FROM tables_cursor INTO @tablename
END
PRINT 'All user-defined tables have been dropped from the database.'
DEALLOCATE tables_cursor
AS
exec ('SELECT * FROM '+@TableName)
GO