我尝试查询在其他服务器中组合3表的结果。我的查询正在运行,但需要很长时间才能得到结果(2分钟)。任何人都可以帮我重构查询,使其快速。我不能使用链接服务器。以下是我的询问:
DECLARE @min_price decimal(38,4);
DECLARE @max_price decimal(38,4);
SET @min_price = 1.045;
SET @max_price = 13.855;
SELECT
Image.filename,
Sender.uploder_name,
Receiver.company_name,
Image.price_estimate,
Image.size
FROM
OPENROWSET('SQLNCLI', 'DRIVER={SQL Server};SERVER=ServerName;UID=userID;PWD=password', 'SELECT * from dbName.dbo.image') Image
INNER JOIN OPENROWSET('SQLNCLI', 'DRIVER={SQL Server};SERVER=ServerName;UID=userID;PWD=password', 'SELECT * from dbName.dbo.sender') Sender
ON Image.sender_username = Sender.username
INNER JOIN OPENROWSET('SQLNCLI', 'DRIVER={SQL Server};SERVER=ServerName;UID=userID;PWD=password', 'SELECT * from dbName.dbo.receiver') Receiver
ON Image.receiver_username = Receiver.username
WHERE
Receiver.min_price >= @min_price AND Receiver.max_price <= @max_price
我怀疑使用 OPENROWSET 并且连接几个表是导致这种速度慢的原因,因为我使用此方法只调用1个表,查询结果与此相比非常快。请帮忙。
答案 0 :(得分:6)
将Openrowset
个查询结果插入temp
个表格并使用temp
中的Join
表格
DECLARE @min_price DECIMAL(38, 4);
DECLARE @max_price DECIMAL(38, 4);
SET @min_price = 1.045;
SET @max_price = 13.855;
SELECT *
INTO #Image
FROM OPENROWSET('SQLNCLI',
'DRIVER={SQL Server};SERVER=ServerName;UID=userID;PWD=password',
'SELECT *
FROM dbName.dbo.image')
SELECT *
INTO #Sender
FROM OPENROWSET('SQLNCLI',
'DRIVER={SQL Server};SERVER=ServerName;UID=userID;PWD=password',
'SELECT *
FROM dbName.dbo.sender')
SELECT *
INTO #Reciever
FROM OPENROWSET('SQLNCLI',
'DRIVER={SQL Server};SERVER=ServerName;UID=userID;PWD=password',
'SELECT *
FROM dbName.dbo.receiver')
WHERE min_price >= @min_price
AND max_price <= @max_price
或者如果所有3个表都来自同一个服务器,那么也尝试这个
SELECT *
FROM OPENROWSET('SQLNCLI',
'DRIVER={SQL Server};SERVER=ServerName;UID=userID;PWD=password',
'SELECT i.filename,
s.uploder_name,
r.company_name,
i.price_estimate,
i.size
FROM Image i
INNER JOIN Sender s
ON i.sender_username = s.username
INNER JOIN Receiver r
ON i.receiver_username = r.username ')