Laura_Li
Laura_Li

Reputation: 177

OpenQuery in SQL Server

I don't know how to config the OpenQuery function.

I want to use OpenQuery to query database in test project. But I don't know how config the servername param

DECLARE @Sql varchar(max)
DECLARE @SQLExcuteSentence varchar(max)

SET @Sql = 'declare @UserID INT 
select @UserID = 1

declare @TotalGroupByFields nvarchar(2000)
select @TotalGroupByFields = ''Media''

declare @CostDataFileds nvarchar(2000)
select @CostDataFileds = ''''

declare @OtherDataFields nvarchar(max)
select @OtherDataFields = ''MonitoringSpotNumber,MonitoringTotalSeconds,BaseCost,ColourLoading,PositionLoading,WeekendLoading,Discount''

declare @MasterFilterId nvarchar(max)
select @MasterFilterId =''DateRange=20060601-20121231''+char(13)+''IncludeGuests=0''

declare @RatingTargetId nvarchar(2000)
select @RatingTargetId =''''

declare @IsEnableFinancialCloseDate INT
select @IsEnableFinancialCloseDate = 0

declare @MasterDisplayFormat nvarchar(2000)
select @MasterDisplayFormat = ''5''

exec [dbo].[USP_MatrixReport] @UserID, @TotalGroupByFields, @CostDataFileds, @OtherDataFields,  @MasterFilterId, @RatingTargetId, @IsEnableFinancialCloseDate, @MasterDisplayFormat, 0'

SET @SQLExcuteSentence = 'SELECT * FROM OPENQUERY(SQLConn,' + '''' + @Sql + '''' + ')'
EXEC (@SQLExcuteSentence);

the SQLConn is what??

Upvotes: 0

Views: 7737

Answers (2)

Kamil
Kamil

Reputation: 13931

Without SQL Server Management Studio it looks like this for localhost:

EXEC sp_addlinkedserver
@server='LOCALSERVER',               -- name definition for later use in OpenQuery
@srvproduct='SQLSERVER',             
@provider='SQLNCLI',                 -- provider name
@datasrc='SERVERNAME\INSTANCENAME'   -- im not sure if there should be '\' or not

Other example with excel file (based on Manoj code):

EXEC sp_addLinkedServer
@server= N'XLSX_2010',
@srvproduct = N'Excel',
@provider = N'Microsoft.ACE.OLEDB.12.0',
@datasrc = N'C:\Users\SomeUser\Desktop\file.xlsx',
@provstr = N'Excel 12.0; HDR=Yes';

Example for localhost with SQL Server Management Studio and without:

http://sqlserverplanet.com/sql-server/local-linked-server

Upvotes: 1

SchmitzIT
SchmitzIT

Reputation: 9552

OPENQUERY requires you first set up a linked server, using sp_addlinkedserver. That is where the connectionstring will be set up.

After that, you can use OPENQUERY to fire a query against the linked server.

Upvotes: 2

Related Questions