Sql-Server

表連接

  • July 27, 2016

我想要一個動態查詢,我可以根據目前月份連接我的表。我想為我的 FROM 和 JOIN 語句添加一個變數。

DECLARE @month_number AS VARCHAR(2);
DECLARE @table_name AS VARCHAR(15);
DECLARE @table AS VARCHAR(MAX);
SET @month_number = (SELECT month(getdate()));
SET @table_name = 'Sessions_month_'
SET @table = @table_name+@month_number;

SELECT * FROM Sessions_month_+@month_number where id = (SELECT id FROM Sessions_month_+@month_number WHERE Contact = 2);

或者我應該這樣做:

https://stackoverflow.com/questions/19939380/how-to-form-a-table-name-from-concatenating-strings-in-select-statement-in-sql-2

我不是在這裡判斷使用動態sql是否是一個好主意,但只是針對您的問題,您可以使用以下程式碼來達到您的目標

DECLARE @month_number AS VARCHAR(2);
DECLARE @table_name AS VARCHAR(15);
DECLARE @table AS VARCHAR(MAX);
declare @qry nvarchar(max);
SET @month_number =  month(getdate());
SET @table_name = 'Sessions_month_'
SET @table = @table_name+@month_number;

set @qry='SELECT * FROM Sessions_month_' + @month_number +' where id = (SELECT id FROM Sessions_month_'+@month_number +' WHERE Contact = 2);'
exec sp_executesql @qry;
go

引用自:https://dba.stackexchange.com/questions/145136