Creating Stored Procedure in local db that references tables in linked serverLinked tables versus stored procedure performance in MySQLLocal login impersonation not working with a linked serverRunning a Job from a Stored Procedure in another server?Stored Procedure against Linked ServerCreating an SSIS package that uses a stored procedureError updating zoned field from SQL Server stored procedure linked server to iSeriesCreating a Linked Server that Points to ItselfCreating Stored Procedure with TableName as parameterExecute stored procedure remotely using linked serverAlter stored procedure - linked server not connected
Is there a realtime, uncut video of Saturn V ignition through tower clear?
Warped chessboard
How would a physicist explain this starship engine?
Vehemently against code formatting
Eigenvalues of the Laplace-Beltrami operator on a compact Riemannnian manifold
Removing Doubles Destroy Topology
Expand a hexagon
pwaS eht tirsf dna tasl setterl fo hace dorw
Why use nominative in Coniugatio periphrastica passiva?
How to play vs. 1.e4 e5 2.Nf3 Nc6 3.Bc4 d6?
How to counter "I don't like your tone" in a work conversation?
What is this dime sized black bug with white on the segments near Loveland Colorodao?
Is there a way to generate a mapping graph like this?
Why "strap-on" boosters, and how do other people say it?
How to become an Editorial board member?
If the Charles SSL Proxy shows me sensitive data, is that data insecure/exposed?
Does George B Sperry logo on fold case for photos indicate photographer or case manufacturer?
Simple Arithmetic Puzzle 7. Or is it?
How do you cope with rejection?
How did Jean Parisot de Valette, 49th Grand Master of the Order of Malta, die?
Keeping the dodos out of the field
Salesforce bug enabled "Modify All"
Does science define life as "beginning at conception"?
US F1 Visa grace period attending a conference
Creating Stored Procedure in local db that references tables in linked server
Linked tables versus stored procedure performance in MySQLLocal login impersonation not working with a linked serverRunning a Job from a Stored Procedure in another server?Stored Procedure against Linked ServerCreating an SSIS package that uses a stored procedureError updating zoned field from SQL Server stored procedure linked server to iSeriesCreating a Linked Server that Points to ItselfCreating Stored Procedure with TableName as parameterExecute stored procedure remotely using linked serverAlter stored procedure - linked server not connected
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I currently have a local server linked to a remote server.
Is it possible to create a stored procedure within the local server, but querying data from tables within the linked server. I am aware there may be performance issues, but I am reluctant to create the sp on the linked server as it would require obtaining permissions to do so.
I believe my problem is syntax but I cannot identify exactly what,
USE [LOCALDB] --my local database or should I reference linked server db here
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[mystoredprocedure]
DECLARE @linkedserv NVARCHAR(150)
DECLARE @linkeddb NVARCHAR(150)
SET @linkedserv = 'HOSTNAMESERVER';
SET @linkeddb = 'remotedb';
SELECT (CASE LTRIM(RTRIM([COLUMN1]))
WHEN '' Then ''
WHEN 'THIS' THEN 'THAT'
WHEN 'NOW' THEN 'NEVER'
ELSE 'OTHER' END) [Options]
INTO #TempTable
FROM @linkedserv.@linkeddb.dbo.TableOnLinkedServer --is this an issue?
FULL OUTER JOIN OtherTableOnLinkedServer ON TableOnLinkedServer.COUMN1 =
OtherTableOnLinkedServer.COLUMN0
The linked servers db and it's tables are queried multiple times throughout the sp so finding a shorthand way of referencing them would be great,
Cheers
sql-server stored-procedures linked-server
add a comment |
I currently have a local server linked to a remote server.
Is it possible to create a stored procedure within the local server, but querying data from tables within the linked server. I am aware there may be performance issues, but I am reluctant to create the sp on the linked server as it would require obtaining permissions to do so.
I believe my problem is syntax but I cannot identify exactly what,
USE [LOCALDB] --my local database or should I reference linked server db here
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[mystoredprocedure]
DECLARE @linkedserv NVARCHAR(150)
DECLARE @linkeddb NVARCHAR(150)
SET @linkedserv = 'HOSTNAMESERVER';
SET @linkeddb = 'remotedb';
SELECT (CASE LTRIM(RTRIM([COLUMN1]))
WHEN '' Then ''
WHEN 'THIS' THEN 'THAT'
WHEN 'NOW' THEN 'NEVER'
ELSE 'OTHER' END) [Options]
INTO #TempTable
FROM @linkedserv.@linkeddb.dbo.TableOnLinkedServer --is this an issue?
FULL OUTER JOIN OtherTableOnLinkedServer ON TableOnLinkedServer.COUMN1 =
OtherTableOnLinkedServer.COLUMN0
The linked servers db and it's tables are queried multiple times throughout the sp so finding a shorthand way of referencing them would be great,
Cheers
sql-server stored-procedures linked-server
2
You are close, but basically if you want to pass in parameters of the linked server to query, the SQL you execute will need to be dynamic SQL.
– Shaulinator
May 7 at 16:04
2
What error(s) are you getting?
– John Eisbrener
May 7 at 16:13
1
have a look at synonyms docs.microsoft.com/en-us/sql/relational-databases/synonyms/…
– Bob Klimes
May 7 at 19:27
@BobKlimes I managed to achieve this using the selected answer, However, as an opportunity to try something different I used synonyms in another example annd achieved the same results with less code - I followed the outline in this article sqlblog.toolsoftonline.com/?p=78
– edwardinchains
May 8 at 14:12
1
If the linked server name and database are fixed, a synonym will work. With the server name and database as variables, though, the implication is that those would be, well, variable. I suppose you could drop and re-create the synonyms every time, which would lead to similar code anyway. If the server name and database name are fixed, I see no need to use variables at all, since the additional code isn't justified by the savings in typing the name multiple times. YMMV.
– Aaron Bertrand♦
May 8 at 16:00
add a comment |
I currently have a local server linked to a remote server.
Is it possible to create a stored procedure within the local server, but querying data from tables within the linked server. I am aware there may be performance issues, but I am reluctant to create the sp on the linked server as it would require obtaining permissions to do so.
I believe my problem is syntax but I cannot identify exactly what,
USE [LOCALDB] --my local database or should I reference linked server db here
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[mystoredprocedure]
DECLARE @linkedserv NVARCHAR(150)
DECLARE @linkeddb NVARCHAR(150)
SET @linkedserv = 'HOSTNAMESERVER';
SET @linkeddb = 'remotedb';
SELECT (CASE LTRIM(RTRIM([COLUMN1]))
WHEN '' Then ''
WHEN 'THIS' THEN 'THAT'
WHEN 'NOW' THEN 'NEVER'
ELSE 'OTHER' END) [Options]
INTO #TempTable
FROM @linkedserv.@linkeddb.dbo.TableOnLinkedServer --is this an issue?
FULL OUTER JOIN OtherTableOnLinkedServer ON TableOnLinkedServer.COUMN1 =
OtherTableOnLinkedServer.COLUMN0
The linked servers db and it's tables are queried multiple times throughout the sp so finding a shorthand way of referencing them would be great,
Cheers
sql-server stored-procedures linked-server
I currently have a local server linked to a remote server.
Is it possible to create a stored procedure within the local server, but querying data from tables within the linked server. I am aware there may be performance issues, but I am reluctant to create the sp on the linked server as it would require obtaining permissions to do so.
I believe my problem is syntax but I cannot identify exactly what,
USE [LOCALDB] --my local database or should I reference linked server db here
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[mystoredprocedure]
DECLARE @linkedserv NVARCHAR(150)
DECLARE @linkeddb NVARCHAR(150)
SET @linkedserv = 'HOSTNAMESERVER';
SET @linkeddb = 'remotedb';
SELECT (CASE LTRIM(RTRIM([COLUMN1]))
WHEN '' Then ''
WHEN 'THIS' THEN 'THAT'
WHEN 'NOW' THEN 'NEVER'
ELSE 'OTHER' END) [Options]
INTO #TempTable
FROM @linkedserv.@linkeddb.dbo.TableOnLinkedServer --is this an issue?
FULL OUTER JOIN OtherTableOnLinkedServer ON TableOnLinkedServer.COUMN1 =
OtherTableOnLinkedServer.COLUMN0
The linked servers db and it's tables are queried multiple times throughout the sp so finding a shorthand way of referencing them would be great,
Cheers
sql-server stored-procedures linked-server
sql-server stored-procedures linked-server
asked May 7 at 15:56
edwardinchainsedwardinchains
284
284
2
You are close, but basically if you want to pass in parameters of the linked server to query, the SQL you execute will need to be dynamic SQL.
– Shaulinator
May 7 at 16:04
2
What error(s) are you getting?
– John Eisbrener
May 7 at 16:13
1
have a look at synonyms docs.microsoft.com/en-us/sql/relational-databases/synonyms/…
– Bob Klimes
May 7 at 19:27
@BobKlimes I managed to achieve this using the selected answer, However, as an opportunity to try something different I used synonyms in another example annd achieved the same results with less code - I followed the outline in this article sqlblog.toolsoftonline.com/?p=78
– edwardinchains
May 8 at 14:12
1
If the linked server name and database are fixed, a synonym will work. With the server name and database as variables, though, the implication is that those would be, well, variable. I suppose you could drop and re-create the synonyms every time, which would lead to similar code anyway. If the server name and database name are fixed, I see no need to use variables at all, since the additional code isn't justified by the savings in typing the name multiple times. YMMV.
– Aaron Bertrand♦
May 8 at 16:00
add a comment |
2
You are close, but basically if you want to pass in parameters of the linked server to query, the SQL you execute will need to be dynamic SQL.
– Shaulinator
May 7 at 16:04
2
What error(s) are you getting?
– John Eisbrener
May 7 at 16:13
1
have a look at synonyms docs.microsoft.com/en-us/sql/relational-databases/synonyms/…
– Bob Klimes
May 7 at 19:27
@BobKlimes I managed to achieve this using the selected answer, However, as an opportunity to try something different I used synonyms in another example annd achieved the same results with less code - I followed the outline in this article sqlblog.toolsoftonline.com/?p=78
– edwardinchains
May 8 at 14:12
1
If the linked server name and database are fixed, a synonym will work. With the server name and database as variables, though, the implication is that those would be, well, variable. I suppose you could drop and re-create the synonyms every time, which would lead to similar code anyway. If the server name and database name are fixed, I see no need to use variables at all, since the additional code isn't justified by the savings in typing the name multiple times. YMMV.
– Aaron Bertrand♦
May 8 at 16:00
2
2
You are close, but basically if you want to pass in parameters of the linked server to query, the SQL you execute will need to be dynamic SQL.
– Shaulinator
May 7 at 16:04
You are close, but basically if you want to pass in parameters of the linked server to query, the SQL you execute will need to be dynamic SQL.
– Shaulinator
May 7 at 16:04
2
2
What error(s) are you getting?
– John Eisbrener
May 7 at 16:13
What error(s) are you getting?
– John Eisbrener
May 7 at 16:13
1
1
have a look at synonyms docs.microsoft.com/en-us/sql/relational-databases/synonyms/…
– Bob Klimes
May 7 at 19:27
have a look at synonyms docs.microsoft.com/en-us/sql/relational-databases/synonyms/…
– Bob Klimes
May 7 at 19:27
@BobKlimes I managed to achieve this using the selected answer, However, as an opportunity to try something different I used synonyms in another example annd achieved the same results with less code - I followed the outline in this article sqlblog.toolsoftonline.com/?p=78
– edwardinchains
May 8 at 14:12
@BobKlimes I managed to achieve this using the selected answer, However, as an opportunity to try something different I used synonyms in another example annd achieved the same results with less code - I followed the outline in this article sqlblog.toolsoftonline.com/?p=78
– edwardinchains
May 8 at 14:12
1
1
If the linked server name and database are fixed, a synonym will work. With the server name and database as variables, though, the implication is that those would be, well, variable. I suppose you could drop and re-create the synonyms every time, which would lead to similar code anyway. If the server name and database name are fixed, I see no need to use variables at all, since the additional code isn't justified by the savings in typing the name multiple times. YMMV.
– Aaron Bertrand♦
May 8 at 16:00
If the linked server name and database are fixed, a synonym will work. With the server name and database as variables, though, the implication is that those would be, well, variable. I suppose you could drop and re-create the synonyms every time, which would lead to similar code anyway. If the server name and database name are fixed, I see no need to use variables at all, since the additional code isn't justified by the savings in typing the name multiple times. YMMV.
– Aaron Bertrand♦
May 8 at 16:00
add a comment |
1 Answer
1
active
oldest
votes
You can't parameterize entity names into a T-SQL statement. In order to do this you need to (a) create the #temp table first, and (b) use dynamic SQL. Here is one approach:
CREATE PROCEDURE [dbo].[mystoredprocedure]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @exec nvarchar(256),
@linkedserv nvarchar(150),
@linkeddb nvarchar(150),
@sql nvarchar(max);
SELECT @linkedserv = N'HOSTNAMESERVER',
@linkeddb = N'remotedb';
SELECT @exec = QUOTENAME(@linkedserv) + N'.'
+ QUOTENAME(@linkeddb) + N'.sys.sp_executesql';
CREATE TABLE #TempTable([Options] varchar(64));
SELECT @sql = N'SELECT (CASE LTRIM(RTRIM(ot.[COLUMN1]))
WHEN '''' THEN ''''
WHEN ''THIS'' THEN ''THAT''
WHEN ''NOW'' THEN ''NEVER''
ELSE ''OTHER'' END) AS [Options]
FROM dbo.TableOnLinkedServer AS t
FULL OUTER JOIN dbo.OtherTableOnLinkedServer AS ot
ON t.COLUMN1 = ot.COLUMN0;';
INSERT #TempTable([Options]) EXEC @exec @sql;
SELECT * FROM #TempTable;
END
GO
You could do it all inside dynamic SQL, so if knowing the columns up front is a challenge, there is a way. But it's messy, assuming you actually need a #temp table, because then everything you do with #TempTable
has to be done inside the dynamic SQL.
CREATE PROCEDURE [dbo].[mystoredprocedure]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @exec nvarchar(256),
@linkedserv nvarchar(150),
@linkeddb nvarchar(150),
@sql nvarchar(max);
SELECT @linkedserv = N'HOSTNAMESERVER',
@linkeddb = N'remotedb';
SELECT @exec = QUOTENAME(@linkedserv) + N'.'
+ QUOTENAME(@linkeddb) + N'.sys.sp_executesql';
SELECT @sql = N'SELECT (CASE LTRIM(RTRIM(ot.[COLUMN1]))
WHEN '''' THEN ''''
WHEN ''THIS'' THEN ''THAT''
WHEN ''NOW'' THEN ''NEVER''
ELSE ''OTHER'' END) AS [Options]
INTO #TempTable
FROM dbo.TableOnLinkedServer AS t
FULL OUTER JOIN dbo.OtherTableOnLinkedServer AS ot
ON t.COLUMN1 = ot.COLUMN0;
SELECT * FROM #TempTable;';
EXEC @exec @sql;
END
GO
Please look at the obligatory Erland Sommarskog article on dynamic T-SQL to ensure you don't end up creating an embarrassing SQL Injection vulnerability.
Excellent - This worked a charm, as I mentioned in a comment above - I also rewrote the query using synonyms - which also achieved the same results.
– edwardinchains
May 8 at 14:14
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "182"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f237562%2fcreating-stored-procedure-in-local-db-that-references-tables-in-linked-server%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can't parameterize entity names into a T-SQL statement. In order to do this you need to (a) create the #temp table first, and (b) use dynamic SQL. Here is one approach:
CREATE PROCEDURE [dbo].[mystoredprocedure]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @exec nvarchar(256),
@linkedserv nvarchar(150),
@linkeddb nvarchar(150),
@sql nvarchar(max);
SELECT @linkedserv = N'HOSTNAMESERVER',
@linkeddb = N'remotedb';
SELECT @exec = QUOTENAME(@linkedserv) + N'.'
+ QUOTENAME(@linkeddb) + N'.sys.sp_executesql';
CREATE TABLE #TempTable([Options] varchar(64));
SELECT @sql = N'SELECT (CASE LTRIM(RTRIM(ot.[COLUMN1]))
WHEN '''' THEN ''''
WHEN ''THIS'' THEN ''THAT''
WHEN ''NOW'' THEN ''NEVER''
ELSE ''OTHER'' END) AS [Options]
FROM dbo.TableOnLinkedServer AS t
FULL OUTER JOIN dbo.OtherTableOnLinkedServer AS ot
ON t.COLUMN1 = ot.COLUMN0;';
INSERT #TempTable([Options]) EXEC @exec @sql;
SELECT * FROM #TempTable;
END
GO
You could do it all inside dynamic SQL, so if knowing the columns up front is a challenge, there is a way. But it's messy, assuming you actually need a #temp table, because then everything you do with #TempTable
has to be done inside the dynamic SQL.
CREATE PROCEDURE [dbo].[mystoredprocedure]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @exec nvarchar(256),
@linkedserv nvarchar(150),
@linkeddb nvarchar(150),
@sql nvarchar(max);
SELECT @linkedserv = N'HOSTNAMESERVER',
@linkeddb = N'remotedb';
SELECT @exec = QUOTENAME(@linkedserv) + N'.'
+ QUOTENAME(@linkeddb) + N'.sys.sp_executesql';
SELECT @sql = N'SELECT (CASE LTRIM(RTRIM(ot.[COLUMN1]))
WHEN '''' THEN ''''
WHEN ''THIS'' THEN ''THAT''
WHEN ''NOW'' THEN ''NEVER''
ELSE ''OTHER'' END) AS [Options]
INTO #TempTable
FROM dbo.TableOnLinkedServer AS t
FULL OUTER JOIN dbo.OtherTableOnLinkedServer AS ot
ON t.COLUMN1 = ot.COLUMN0;
SELECT * FROM #TempTable;';
EXEC @exec @sql;
END
GO
Please look at the obligatory Erland Sommarskog article on dynamic T-SQL to ensure you don't end up creating an embarrassing SQL Injection vulnerability.
Excellent - This worked a charm, as I mentioned in a comment above - I also rewrote the query using synonyms - which also achieved the same results.
– edwardinchains
May 8 at 14:14
add a comment |
You can't parameterize entity names into a T-SQL statement. In order to do this you need to (a) create the #temp table first, and (b) use dynamic SQL. Here is one approach:
CREATE PROCEDURE [dbo].[mystoredprocedure]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @exec nvarchar(256),
@linkedserv nvarchar(150),
@linkeddb nvarchar(150),
@sql nvarchar(max);
SELECT @linkedserv = N'HOSTNAMESERVER',
@linkeddb = N'remotedb';
SELECT @exec = QUOTENAME(@linkedserv) + N'.'
+ QUOTENAME(@linkeddb) + N'.sys.sp_executesql';
CREATE TABLE #TempTable([Options] varchar(64));
SELECT @sql = N'SELECT (CASE LTRIM(RTRIM(ot.[COLUMN1]))
WHEN '''' THEN ''''
WHEN ''THIS'' THEN ''THAT''
WHEN ''NOW'' THEN ''NEVER''
ELSE ''OTHER'' END) AS [Options]
FROM dbo.TableOnLinkedServer AS t
FULL OUTER JOIN dbo.OtherTableOnLinkedServer AS ot
ON t.COLUMN1 = ot.COLUMN0;';
INSERT #TempTable([Options]) EXEC @exec @sql;
SELECT * FROM #TempTable;
END
GO
You could do it all inside dynamic SQL, so if knowing the columns up front is a challenge, there is a way. But it's messy, assuming you actually need a #temp table, because then everything you do with #TempTable
has to be done inside the dynamic SQL.
CREATE PROCEDURE [dbo].[mystoredprocedure]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @exec nvarchar(256),
@linkedserv nvarchar(150),
@linkeddb nvarchar(150),
@sql nvarchar(max);
SELECT @linkedserv = N'HOSTNAMESERVER',
@linkeddb = N'remotedb';
SELECT @exec = QUOTENAME(@linkedserv) + N'.'
+ QUOTENAME(@linkeddb) + N'.sys.sp_executesql';
SELECT @sql = N'SELECT (CASE LTRIM(RTRIM(ot.[COLUMN1]))
WHEN '''' THEN ''''
WHEN ''THIS'' THEN ''THAT''
WHEN ''NOW'' THEN ''NEVER''
ELSE ''OTHER'' END) AS [Options]
INTO #TempTable
FROM dbo.TableOnLinkedServer AS t
FULL OUTER JOIN dbo.OtherTableOnLinkedServer AS ot
ON t.COLUMN1 = ot.COLUMN0;
SELECT * FROM #TempTable;';
EXEC @exec @sql;
END
GO
Please look at the obligatory Erland Sommarskog article on dynamic T-SQL to ensure you don't end up creating an embarrassing SQL Injection vulnerability.
Excellent - This worked a charm, as I mentioned in a comment above - I also rewrote the query using synonyms - which also achieved the same results.
– edwardinchains
May 8 at 14:14
add a comment |
You can't parameterize entity names into a T-SQL statement. In order to do this you need to (a) create the #temp table first, and (b) use dynamic SQL. Here is one approach:
CREATE PROCEDURE [dbo].[mystoredprocedure]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @exec nvarchar(256),
@linkedserv nvarchar(150),
@linkeddb nvarchar(150),
@sql nvarchar(max);
SELECT @linkedserv = N'HOSTNAMESERVER',
@linkeddb = N'remotedb';
SELECT @exec = QUOTENAME(@linkedserv) + N'.'
+ QUOTENAME(@linkeddb) + N'.sys.sp_executesql';
CREATE TABLE #TempTable([Options] varchar(64));
SELECT @sql = N'SELECT (CASE LTRIM(RTRIM(ot.[COLUMN1]))
WHEN '''' THEN ''''
WHEN ''THIS'' THEN ''THAT''
WHEN ''NOW'' THEN ''NEVER''
ELSE ''OTHER'' END) AS [Options]
FROM dbo.TableOnLinkedServer AS t
FULL OUTER JOIN dbo.OtherTableOnLinkedServer AS ot
ON t.COLUMN1 = ot.COLUMN0;';
INSERT #TempTable([Options]) EXEC @exec @sql;
SELECT * FROM #TempTable;
END
GO
You could do it all inside dynamic SQL, so if knowing the columns up front is a challenge, there is a way. But it's messy, assuming you actually need a #temp table, because then everything you do with #TempTable
has to be done inside the dynamic SQL.
CREATE PROCEDURE [dbo].[mystoredprocedure]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @exec nvarchar(256),
@linkedserv nvarchar(150),
@linkeddb nvarchar(150),
@sql nvarchar(max);
SELECT @linkedserv = N'HOSTNAMESERVER',
@linkeddb = N'remotedb';
SELECT @exec = QUOTENAME(@linkedserv) + N'.'
+ QUOTENAME(@linkeddb) + N'.sys.sp_executesql';
SELECT @sql = N'SELECT (CASE LTRIM(RTRIM(ot.[COLUMN1]))
WHEN '''' THEN ''''
WHEN ''THIS'' THEN ''THAT''
WHEN ''NOW'' THEN ''NEVER''
ELSE ''OTHER'' END) AS [Options]
INTO #TempTable
FROM dbo.TableOnLinkedServer AS t
FULL OUTER JOIN dbo.OtherTableOnLinkedServer AS ot
ON t.COLUMN1 = ot.COLUMN0;
SELECT * FROM #TempTable;';
EXEC @exec @sql;
END
GO
Please look at the obligatory Erland Sommarskog article on dynamic T-SQL to ensure you don't end up creating an embarrassing SQL Injection vulnerability.
You can't parameterize entity names into a T-SQL statement. In order to do this you need to (a) create the #temp table first, and (b) use dynamic SQL. Here is one approach:
CREATE PROCEDURE [dbo].[mystoredprocedure]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @exec nvarchar(256),
@linkedserv nvarchar(150),
@linkeddb nvarchar(150),
@sql nvarchar(max);
SELECT @linkedserv = N'HOSTNAMESERVER',
@linkeddb = N'remotedb';
SELECT @exec = QUOTENAME(@linkedserv) + N'.'
+ QUOTENAME(@linkeddb) + N'.sys.sp_executesql';
CREATE TABLE #TempTable([Options] varchar(64));
SELECT @sql = N'SELECT (CASE LTRIM(RTRIM(ot.[COLUMN1]))
WHEN '''' THEN ''''
WHEN ''THIS'' THEN ''THAT''
WHEN ''NOW'' THEN ''NEVER''
ELSE ''OTHER'' END) AS [Options]
FROM dbo.TableOnLinkedServer AS t
FULL OUTER JOIN dbo.OtherTableOnLinkedServer AS ot
ON t.COLUMN1 = ot.COLUMN0;';
INSERT #TempTable([Options]) EXEC @exec @sql;
SELECT * FROM #TempTable;
END
GO
You could do it all inside dynamic SQL, so if knowing the columns up front is a challenge, there is a way. But it's messy, assuming you actually need a #temp table, because then everything you do with #TempTable
has to be done inside the dynamic SQL.
CREATE PROCEDURE [dbo].[mystoredprocedure]
AS
BEGIN
SET NOCOUNT ON;
DECLARE @exec nvarchar(256),
@linkedserv nvarchar(150),
@linkeddb nvarchar(150),
@sql nvarchar(max);
SELECT @linkedserv = N'HOSTNAMESERVER',
@linkeddb = N'remotedb';
SELECT @exec = QUOTENAME(@linkedserv) + N'.'
+ QUOTENAME(@linkeddb) + N'.sys.sp_executesql';
SELECT @sql = N'SELECT (CASE LTRIM(RTRIM(ot.[COLUMN1]))
WHEN '''' THEN ''''
WHEN ''THIS'' THEN ''THAT''
WHEN ''NOW'' THEN ''NEVER''
ELSE ''OTHER'' END) AS [Options]
INTO #TempTable
FROM dbo.TableOnLinkedServer AS t
FULL OUTER JOIN dbo.OtherTableOnLinkedServer AS ot
ON t.COLUMN1 = ot.COLUMN0;
SELECT * FROM #TempTable;';
EXEC @exec @sql;
END
GO
Please look at the obligatory Erland Sommarskog article on dynamic T-SQL to ensure you don't end up creating an embarrassing SQL Injection vulnerability.
edited May 7 at 17:01
Max Vernon
53.4k13116235
53.4k13116235
answered May 7 at 16:27
Aaron Bertrand♦Aaron Bertrand
156k18303508
156k18303508
Excellent - This worked a charm, as I mentioned in a comment above - I also rewrote the query using synonyms - which also achieved the same results.
– edwardinchains
May 8 at 14:14
add a comment |
Excellent - This worked a charm, as I mentioned in a comment above - I also rewrote the query using synonyms - which also achieved the same results.
– edwardinchains
May 8 at 14:14
Excellent - This worked a charm, as I mentioned in a comment above - I also rewrote the query using synonyms - which also achieved the same results.
– edwardinchains
May 8 at 14:14
Excellent - This worked a charm, as I mentioned in a comment above - I also rewrote the query using synonyms - which also achieved the same results.
– edwardinchains
May 8 at 14:14
add a comment |
Thanks for contributing an answer to Database Administrators Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f237562%2fcreating-stored-procedure-in-local-db-that-references-tables-in-linked-server%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
You are close, but basically if you want to pass in parameters of the linked server to query, the SQL you execute will need to be dynamic SQL.
– Shaulinator
May 7 at 16:04
2
What error(s) are you getting?
– John Eisbrener
May 7 at 16:13
1
have a look at synonyms docs.microsoft.com/en-us/sql/relational-databases/synonyms/…
– Bob Klimes
May 7 at 19:27
@BobKlimes I managed to achieve this using the selected answer, However, as an opportunity to try something different I used synonyms in another example annd achieved the same results with less code - I followed the outline in this article sqlblog.toolsoftonline.com/?p=78
– edwardinchains
May 8 at 14:12
1
If the linked server name and database are fixed, a synonym will work. With the server name and database as variables, though, the implication is that those would be, well, variable. I suppose you could drop and re-create the synonyms every time, which would lead to similar code anyway. If the server name and database name are fixed, I see no need to use variables at all, since the additional code isn't justified by the savings in typing the name multiple times. YMMV.
– Aaron Bertrand♦
May 8 at 16:00