如何从EXEC sp_executesql获取返回值

时间:2015-10-07 18:36:50

标签: sql-server sp-executesql

如何从EXEC sp_executesql @OpenQry获取返回值,以便检查IF EXISTS中是否存在该值?

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 TableName=@TableName)

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

1 个答案:

答案 0 :(得分:0)

你只需要在sp_executesql

之前放置你想要接收的变量de return value

尝试使用代码,让我知道是否有效

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 TableName=@TableName )
*/
--maybe you dont need check if the table name existis, jut try this

IF EXISTS (SELECT TableName FROM dbo.table WHERE TableName=@TableNameToDrop )
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

此致