T-SQL:SELECT中动态变量的问题

时间:2017-07-18 12:13:59

标签: sql sql-server tsql

我想将以下select的结果存储到变量中。

SET @SearchSchema = '(SELECT REPLACE(name,''Change Log Setup'', ''Change Log Entry'') as Name  FROM ['+@DBName+'].sys.tables where name LIKE ''%$Change Log Setup'')'

我也尝试过exec sp_executesql。

以下是整个代码:

DECLARE @DBName VARCHAR(5000);
DECLARE @period VARCHAR(5000);
DECLARE @SQLEXE VARCHAR(8000);
DECLARE @SearchSchema NVARCHAR(4000);
DECLARE @Authentification VARCHAR(1000);
DECLARE @Path VARCHAR(1000);
DECLARE @ServerName VARCHAR(1000);

SET @period = '''2017-01-01 00:00:00'' AND ''2017-12-31 23:59:59''';    
SET @Path = 'C:\Users\Public\Documents\';                                   
SET @Servername = '-S nav-ey-demo2\NAVDEMO';

SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE [' + @DBName+']'); Select db_name();

SET @SearchSchema = '(SELECT REPLACE(name,''Change Log Setup'', ''Change Log Entry'') as Name  FROM ['+@DBName+'].sys.tables where name LIKE ''%$Change Log Setup'')'

如果我使用

SELECT @SearchSchema

出现正确的值。

使用

PRINT '@SEARCHSCHEMA ' + @SearchSchema

显示SELECT字符串:

SEARCHSCHEMA (SELECT REPLACE(name,'Change Log Setup', 'Change Log Entry') as Name  FROM [Demo Database NAV (10-0)].sys.tables where name LIKE '%$Change Log Setup')

1 个答案:

答案 0 :(得分:2)

首先,您必须构建动态查询,然后执行它,调用sp_executesql,然后将结果存储到变量中。

DECLARE @DBName VARCHAR(5000);
DECLARE @period VARCHAR(5000);
DECLARE @SQLEXE VARCHAR(8000);
DECLARE @SearchSchema NVARCHAR(4000);
DECLARE @Authentification VARCHAR(1000);
DECLARE @Path VARCHAR(1000);
DECLARE @ServerName VARCHAR(1000);
DECLARE @QueryResult NVARCHAR(4000); 

SET @period = '''2017-01-01 00:00:00'' AND ''2017-12-31 23:59:59''';    --DON'T change the audit period. It is only allowed by the EY auditor. A change of this value can be easily detected.
SET @Path = 'C:\Users\Public\Documents\';                                   --you can change the path directory
SET @Servername = '-S nav-ey-demo2\NAVDEMO';

SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE [' + @DBName+']'); Select db_name();

SET @SearchSchema = '(SELECT @ResultOut = REPLACE(name,''Change Log Setup'', ''Change Log Entry'') as Name  FROM ['+@DBName+'].sys.tables where name LIKE ''%$Change Log Setup'')'

EXEC sp_executesql @SearchSchema, '@ResultOut NVARCHAR(4000) OUTPUT', @ResultOut=@QueryResult OUTPUT;

SELECT @QueryResult;