Sql server:如何从sql字符串中获取值

时间:2015-10-02 20:24:48

标签: sql-server

此sql语句不起作用。在EXEC(@strSql)之后,我看到0或1作为结果,所以我继续使用IF语句,但它没有像我预期的那样工作。它不会从IF声明中采取行动。 此外,有没有办法使查询动态,所以我可以检查多个表?

Declare @strSql varchar(1000),
@TableName varchar(100),
@linkedServer varchar(100)

Set @TableName='tablename'
Set @linkedServer='linkservername'
Set @strSql='Select count(1) as TabExists FROM DBC.TABLES WHERE
      TABLEKIND=''T'' AND DATABASENAME=''databasename'' AND 
      TABLENAME=''tablename'''
SET  @strSql = N'select TabExists from OPENQUERY('+@linkedServer+', ''' + REPLACE(@strSql, '''', '''''') + ''')'
EXEC (@strSql)

IF @strSql = '0'  --table not exist
    create table
IF @strSql = '1'  --table exist
delete data from table

1 个答案:

答案 0 :(得分:0)

而不是尝试

DECLARE @SQL NVARCHAR(MAX) = ''
DECLARE @TabExists BIT;

Set @strSql = 'SELECT @TabExists = CASE WHEN TabExists = 0 THEN 0 ELSE 1 END
        FROM OPENQUERY(' + QUOTENAME(@linkedServer) 
        + ', ''SELECT TabExists = COUNT(*) 
                FROM LinkedDB.INFORMATION_SCHEMA.TABLES
                WHERE TABLE_NAME = ' + @TableName + ');';

EXECUTE sp_executesql @strSQL, N'@TabExists BIT OUTPUT', @TabExists OUT;

IF (@TabExists = 0)
BEGIN
    -- create table
END;