本文介紹了如何在 SQL Server 查詢的 FROM 子句中使用變量?的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我正在創(chuàng)建一個(gè)查詢,該查詢將選擇表中的所有數(shù)據(jù).查詢將根據(jù)我將傳遞給存儲(chǔ)過(guò)程的變量選擇到表中.
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.
在我的例子中.如果我執(zhí)行 example_sp table1
,它將在 table1
中選擇.同樣的事情,如果我使用 example_table table2
,它應(yīng)該選擇 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
這篇關(guān)于如何在 SQL Server 查詢的 FROM 子句中使用變量?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來(lái)源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問(wèn)題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!