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

Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

Bruxelas-Capital Índice Historia | Composición | Situación lingüística | Clima | Cidades irmandadas | Notas | Véxase tamén | Menú de navegacióneO uso das linguas en Bruxelas e a situación do neerlandés"Rexión de Bruxelas Capital"o orixinalSitio da rexiónPáxina de Bruselas no sitio da Oficina de Promoción Turística de Valonia e BruxelasMapa Interactivo da Rexión de Bruxelas-CapitaleeWorldCat332144929079854441105155190212ID28008674080552-90000 0001 0666 3698n94104302ID540940339365017018237

What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company