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 子句中使用变量?


基础教程推荐
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01