我試圖用由SQL查詢檢索的行中的另一個SQL查詢作爲列和表名使用行值在SELECT語句中
例如:
declare @var1 varchar(max)
declare @var2 varchar(max)
declare @result varchar(max)
set @var1 = 'cctl_country'
set @var2 = 'typecode'
set @result = 'select '[email protected]+' from '[email protected]
print @result
在上面的例子中,輸出將是select typecode from cctl_country
。 它也應該像select cctl_country,typecode from cctl_country
一樣。 table_name應該跟在typecode之後。
但是,扭曲的是,@ VAR1是動態的,並不斷變化,這需要從信息架構檢索。 因此,對於@ var1值的每個更改,我需要執行select查詢並將結果集插入到另一個表中。 我在下面的代碼中嘗試了同樣的事情,但我陷入了困境。有一點幫助,將不勝感激
CREATE PROCEDURE usp_try
AS
BEGIN
DECLARE @StartLoop INT
DECLARE @EndLoop INT
DECLARE @esal INT
DECLARE @sqlquery varchar(max)
DECLARE @Result TABLE (table_name nvarchar(100),typecodes nvarchar(100))
DECLARE @InitResult TABLE (id INT IDENTITY(1, 1),
table_name NVARCHAR(50),
typecode NVARCHAR(50))
INSERT INTO @InitResult
select col.TABLE_NAME,'typecodes' as typecodes from [NFUM_Studio].INFORMATION_SCHEMA.COLUMNS col
inner join [NFUM_Studio].INFORMATION_SCHEMA.TABLES tab
on col.TABLE_NAME = tab.TABLE_NAME
where col.COLUMN_NAME = 'typecode'
SELECT @StartLoop = MIN(ID),
@EndLoop = MAX(ID)
FROM @InitResult
WHILE @StartLoop <= @EndLoop
BEGIN
SET @sqlquery = 'insert into @Result
select table_name,typecode from @InitResult'
SET @StartLoop = @StartLoop + 1
END
SELECT *
FROM @Result
END
的幫助下#Result的輸出保持與查詢相同。我期待着前進一步。 –
@Kishanu我誤解了這個問題。小小的一刻,我會更新我的回答 – Hadi
當然@哈迪..我已經更新了上述問題了一下..請你再看一次嗎? –