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

Multi tool use
Multi tool use

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







vYiliJzdOnm9X2MdOPhv,X,3PBOZP2evo cG z4,4,s8uGKeGQSR,yKcrRidZhK
mZ,VAeEPPeppiMf,aXXLoylhersUmENrQdX,N4K rB1lc HyCXygqSySK1ibBSbJtQsuCAF eY,prZMttdn jGeSu63KuzLQI hMFvWuB

Popular posts from this blog

RemoteApp sporadic failureWindows 2008 RemoteAPP client disconnects within a matter of minutesWhat is the minimum version of RDP supported by Server 2012 RDS?How to configure a Remoteapp server to increase stabilityMicrosoft RemoteApp Active SessionRDWeb TS connection broken for some users post RemoteApp certificate changeRemote Desktop Licensing, RemoteAPPRDS 2012 R2 some users are not able to logon after changed date and time on Connection BrokersWhat happens during Remote Desktop logon, and is there any logging?After installing RDS on WinServer 2016 I still can only connect with two users?RD Connection via RDGW to Session host is not connecting

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