How to use variable in FROM clause in SQL Server query?(如何在 SQL Server 查询的 FROM 子句中使用变量?)
问题描述
我正在创建一个查询,该查询将选择表中的所有数据.查询将根据我将传递给存储过程的变量选择到表中.
I am creating a query that will select all data on the table. The query will select to the table base on the variable that I will pass on the stored procedure.
在我的例子中.如果我执行 example_sp table1
,它将在 table1
中选择.同样的事情,如果我使用 example_table table2
,它应该选择 table2
.
Here in my example. If I execute example_sp table1
it will select in table1
. Same thing if I use example_table table2
, it should selecttable2
.
ALTER PROCEDURE example_sp
@type varchar(10), -- value will be `table1` or `table2`
AS
BEGIN
SELECT * FROM @type
END
推荐答案
Gordon 建议的版本略有不同......
A slightly different version of what Gordon has suggested.....
ALTER PROCEDURE example_sp
@TableName SYSNAME --<-- Use appropriate data type for sql server objects
AS
BEGIN
SET NOCOUNT ON;
Declare @Sql NVARCHAR(MAX);
SET @Sql = N' SELECT * FROM ' + QUOTENAME(@TableName)
Exec sp_executesql @Sql
END
这篇关于如何在 SQL Server 查询的 FROM 子句中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 SQL Server 查询的 FROM 子句中使用变量?


基础教程推荐
- oracle区分大小写的原因? 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 在多列上分布任意行 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01