如何在 SQL Server 查询的 FROM 子句中使用变量? [英] How to use variable in FROM clause in SQL Server query?

查看:81
本文介绍了如何在 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 子句中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆