2015-10-07 121 views
0

如何從EXEC sp_executesql @OpenQry獲取返回值,以便我可以檢查IF EXISTS中是否存在該值?如何從EXEC獲取返回值sp_executesql

DECLARE @TableName VARCHAR(25) 
DECLARE @TD_QUERY NVARCHAR(MAX) 

DECLARE CUR_QRY CURSOR FOR 
SELECT TABLENAME FROM dbo.tbl_table 

OPEN CUR_QRY 
FETCH NEXT FROM CUR_QRY INTO @TableName 

WHILE @@FETCH_STATUS = 0 
BEGIN 

SET @OpenQry = 'SELECT * FROM OPENQUERY(linkedserver,''SELECT TABLENAME FROM DBC.TABLES WHERE TABLEKIND=''''T'''' AND DATABASENAME=''''dbname'''' AND TABLENAME=''''' + @TableName + ''''''')' 

EXEC sp_executesql @OpenQry 

IF EXISTS (SELECT @OpenQry) 
AND EXISTS (SELECT TableName FROM dbo.table WHERE [email protected]) 

FETCH NEXT FROM CUR_QRY INTO @TableName 
END 
CLOSE CUR_QRY 
DEALLOCATE CUR_QRY 
+0

你將不得不把你的動態sql的結果放到一個表(持久性,溫度或變量)中。是否有一個原因,你不能只是查詢鏈接服務器?這種光標方法將會讓你的表演失去生命。 –

+0

[如何將sp \ _executesql結果導入變量?](http://stackoverflow.com/questions/803211/how-to-get-sp-executesql-result-into-a-variable) – DeanOC

回答

0

你只需把要sp_executesql的前收到日返回值

嘗試那朵代碼的變量,讓我知道,如果作品

DECLARE @TableName VARCHAR(MAX) 
DECLARE @TableNameToDrop VARCHAR(MAX) --NEW 
DECLARE @TD_QUERY NVARCHAR(MAX) 
DECLARE @OpenQry NVARCHAR(MAX) -- Dont forget to declare this variable 
declare @sqldrop nvarchar(max) 


DECLARE CUR_QRY CURSOR FOR 
SELECT TABLENAME FROM dbo.tbl_table 

OPEN CUR_QRY 
FETCH NEXT FROM CUR_QRY INTO @TableName 

WHILE @@FETCH_STATUS = 0 
BEGIN 

SET @OpenQry = 'SELECT * FROM OPENQUERY(linkedserver,''SELECT TABLENAME FROM DBC.TABLES WHERE TABLEKIND=''''T'''' AND DATABASENAME=''''dbname'''' AND TABLENAME=''''' + @TableName + ''''''')' 

EXEC TableNameToDrop = sp_executesql @OpenQry 

/* 
IF EXISTS (SELECT @OpenQry) 
AND EXISTS (SELECT TableName FROM dbo.table WHERE [email protected]) 
*/ 
--maybe you dont need check if the table name existis, jut try this 

IF EXISTS (SELECT TableName FROM dbo.table WHERE [email protected]) 
BEGIN 
    set @sqldrop = 'drop table '+ @TableNameToDrop 
    EXEC sp_executesql @sqldrop 
END 

FETCH NEXT FROM CUR_QRY INTO @TableName 
END 
CLOSE CUR_QRY 
DEALLOCATE CUR_QRY 

問候

+0

作品!所以在IF EXISTS中,我做IF EXISTS(SELECT @TableName)嗎? – angelcake

+0

此外,IF EXISTS後,我需要執行刪除表EXEC sp_executesql N'EXEC(''DROP TABLE Dbname。'''+ @ TableName +''')AT [linkedserver];'語法似乎不正確,因爲它不會刪除表。你有解決方案嗎? – angelcake

+0

如果您想放置的桌子可以放下,您需要小心。 – Andaramis