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;








5















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










share|improve this question

















  • 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


















5















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










share|improve this question

















  • 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














5












5








5








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










share|improve this question














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






share|improve this question













share|improve this question











share|improve this question




share|improve this question










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













  • 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











1 Answer
1






active

oldest

votes


















8














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.






share|improve this answer

























  • 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











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
);



);













draft saved

draft discarded


















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









8














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.






share|improve this answer

























  • 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















8














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.






share|improve this answer

























  • 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













8












8








8







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.






share|improve this answer















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.







share|improve this answer














share|improve this answer



share|improve this answer








edited May 7 at 17:01









Max Vernon

53.4k13116235




53.4k13116235










answered May 7 at 16:27









Aaron BertrandAaron 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

















  • 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

















draft saved

draft discarded
















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020