How to retrieve return code from sp_addlinkedserver? - sql-server-2000

I am trying to link the server
Exec sp_addlinkedserver 'servername', ......
How will i retrieve its result (return value 0 or 1) in a variable?

Insert into MyTable
exec sp_addlinkedserver 'servername'

Related

Linked servers, results query xp_cmdshell to table migration SQL Server 2005 to SQL Server 2019

I'm migrating procedures from Microsoft SQL Server 2005 to Microsoft SQL Server 2019 and I got stuck while trying insert query result xp_cmdshell in linked servers to table
I'm out of ideas
Old solution in Microsoft SQL Server 2005:
INSERT INTO LOGTABLE (ShopNo,Line) SELECT 1, OUTPUT FROM openquery ([IP_LINKED_SERV],'set fmtonly off; exec master..xp_cmdshell ''type d:\log\file.log'' ')
Microsoft SQL Server 2019 gives me error:
Msg 11519, Level 16, State 1, Procedure
sp_describe_first_result_set, Line 1 [Batch Start Line 0] The metadata could not be determined because statement 'exec master..xp_cmdshell 'type d:\log\file.log'' invokes an extended stored procedure.`
I found a way how to do xp_cmdshell in SQL Server 2019 at linked servers
EXEC ('set fmtonly off;exec master..xp_cmdshell ''type d:\log\file.log'' ') AT [IP_LINKED_SERV]
However I can't insert this results in table
INSERT INTO LOGTABLE (ShopNo,Line) SELECT '998', OUTPUT FROM EXEC ('set fmtonly off;exec master..xp_cmdshell ''type d:\log\file.log'' ') AT [IP_LINKED_SERV]
Incorrect syntax near the keyword 'EXEC'.
part of the procedure in sql2005:
DECLARE TableCursor CURSOR FOR
SELECT IP, SqlUser, SqlPass, Object FROM ..ObjectInfo
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO #Ip, #SqlUser, #SqlPass, #Object
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT #Object
SELECT #PARAMS = ' #tmp_object varchar(5) OUTPUT'
set #SQL = 'INSERT INTO LOGTABLE (Object,Line) SELECT #tmp_object, output FROM openquery (['+#Ip+'],''set fmtonly off;
exec master..xp_cmdshell ''''type d:\log\file.log''''
'')'
BEGIN TRY
EXECUTE sp_executesql #SQL,#PARAMS, #tmp_object = #Object OUTPUT
END TRY
BEGIN CATCH
INSERT INTO LOGTABLE (Object, Line) VALUES(#Object, '-error')
END CATCH```

SELECT specific columns from EXEC stored procedure

I am having an issue trying to SELECT specific columns from an EXEC statement on a stored procedure. I am trying to find the COUNT(*) that the stored procedure returns which I am successfully doing with :
INSERT INTO #temp
EXEC dbo.my_sp
SET #count = (SELECT COUNT(*) FROM #temp)
DELETE FROM #temp
However, this only works if the columns returned match specifically with the table columns and since I am trying to find the count of many different stored procedures (each of which return different columns), I cannot use this method without creating a new table for each stored procedure.
Is there a way I can SELECT specific columns from the EXEC dbo.my_sp?
Create a loopback linked server to the local instance, making sure that data access is enabled. Let's say you have a local named instance called YourServer\SQL2008:
USE [master];
GO
EXEC sp_addlinkedserver
#server = N'LoopbackLocal',
#srvproduct = N'',
#provider = N'SQLNCLI',
#datasrc = N'.\SQL2008',
#catalog = N'tempdb';
GO
EXEC sp_serveroption
#server = N'LoopbackLocal',
#optname = N'collation compatible',
#optvalue = N'true';
GO
EXEC sp_serveroption
#server = N'LoopbackLocal',
#optname = N'data access',
#optvalue = N'true';
GO
EXEC sp_addlinkedsrvlogin
#rmtsrvname = N'LoopbackLocal',
#locallogin = NULL ,
#useself = N'True';
GO
-- you may need to configure other security here
Then you can use OPENQUERY to run a stored procedure as if it were an ad hoc query.
SELECT COUNT(*)
FROM OPENQUERY
(
LoopbackLocal,
'EXEC dbo.my_sp'
) AS y;
Now, if dbo.my_sp dumps information into a #temp table first, you're going to have issues, since it is no longer a block of code that OPENQUERY can process. For example, if you try to execute sp_who2 this way, at least in SQL Server 2012, you will get an error from sp_describe_first_result_set which OPENQUERY has been altered to use (so maybe this works for you now, I don't have 2008 to test, but it will be an issue someday):
Msg 11526, Level 16, State 1, Procedure sp_describe_first_result_set, Line 1
The metadata could not be determined because ... uses a temp table.
If you're going to be doing this a lot, however, why not make specialized stored procedures (or add options to these ones) such that only a count is returned?
Would ##ROWCOUNT work for you?
if OBJECT_ID('SomeProc') is null
exec ('create procedure dbo.SomeProc as select 1 as SomeValue union all select 2 as SomeValue;')
exec dbo.SomeProc
Select ##ROWCOUNT as RowsAffected
http://technet.microsoft.com/en-us/library/ms187316(v=sql.105).aspx

SQL Server dynamic query -- cannot locate linked server

declare #node int = 9044;
DECLARE #sqlCommand NVARCHAR(MAX) =
(
'SELECT * FROM [#node].[database_name].dbo.table_name'
);
DECLARE #paramList NVARCHAR(400) =
(
'#node int'
)
exec sp_executesql #sqlCommand, #paramlist, #node;
So this is the simple query I'm attempting to run. 9044 is fine. Running that query normally works perfectly (obviously I've removed the db and table names). Not entirely sure what is wrong with it. The error I get is:
Msg 7202, Level 11, State 2, Line 1
Could not find server '#node' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers.
Any ideas on how to fix this issue or should I just write the query and use EXEC (#sql)
As per my thinking and test it only allow parameter in query part like in where and other condition.
Try this way.
declare #node int = 9044;
DECLARE #sqlCommand NVARCHAR(MAX) =
(
'SELECT * FROM [#node].[database_name].dbo.table_name'
);
DECLARE #paramList NVARCHAR(400) =
(
'#node int'
)
SET #sqlCommand = REPLACE(#sqlCommand , '#node',#node)
exec sp_executesql #sqlCommand, #paramlist, #node;
You are using 3-dot notation which defines the server.db.table #nodes is looking for a server of this name ...are you looking for this server name dynamically.. the best way would be to create a linked server object or alias and refer to it this was i.e
MyServer = dev-sql-server.AdventureWorks etc
Or you may just need to get rid of the extra [#node].

Execute sybase stored procedure as linked server procedure sql server 2008

EDIT
The final goal is to call a stored procedure hosted in sybase with input and output parameters from SQL Server 2008 via Linked Server
I think title is pretty clear.
My goal is to execute a stored procedure hosted in Sybase SQL Anywhere 8 in SQL Server 2008 through the linked server I already created.
Any SQL query made through the linked server is working.
In addition I was able to execute a function but I don't now how to get the return value like that
EXEC ('CALL "dbname"."procedurename"(''param1'', ''param2'', ''param3'')') AT LinkedServerAlias;
Thanks 4 all your help!
Mauro
can you use four part naming convention?
like
exec LinkedServerName.dbname.dbo.procedurename #param1, #param2, #param3
I was finally able to do it by calling
SELECT * FROM OPENQUERY([LinkedServer], 'SELECT "dbname"."spname"(#p1,#p2, #p3)')
I'll add comments and example as soon as I experiment it.
4 part object names are valid only for SQL Server linked servers.
You have to have your EXEC inside an OPENQUERY
SELECT * FROM OPENQUERY([LinkedServer], 'EXEC MyDB.MyScheme.MyProc.spname #p1, #p2, #p3')
Now, you can't parametrise OPENQUERY calls so you have use dynamic SQL
DECLARE #sql nvarchar(4000), #linkedsql nvarchar(4000)
SET #sql = 'EXEC MyDB.MyScheme.MyProc.spname ' + CAST(#p1value as int) + ...
SET #linkedsql = 'SELECT * FROM OPENQUERY(LinkedServer, ''' + #sql + ''')'
EXEC (#linkedsql)

Execute stored proc with OPENQUERY

I have SQL Server 2008 with a linked Sybase server and I am trying to execute a stored procedure on the Sybase server using OPENQUERY. If I have a stored proc that doesn't take parameters it succeeds fine. If I have a stored proc with parameters it fails. I even tried a very basic stored proc that only took an int an that still failed. Below is the syntax I am using:
select * from
OPENQUERY([LINKSERVER],'exec database.user.my_stored_proc ''AT'',''XXXX%'',''1111'',1')
Msg 7357, Level 16, State 2, Line 3
Cannot process the object "exec database.user.my_stored_proc 'AT','XXXX%','1111',1". The OLE DB provider "ASEOLEDB" for linked server "LINKSERVER" indicates that either the object has no columns or the current user does not have permissions on that object.
As the proc will execute just fine without parameters, I don't think it is a permission issue.
This worked for me,
SELECT * FROM OPENQUERY(LOCALSERVER, 'SET FMTONLY OFF EXEC snr.dbo.GetAllSignals #controlRunId = 25, #experimentRunId = 26')
I was creating temporary tables, and that's why i got access denied
Here is more info http://www.sommarskog.se/share_data.html#OPENQUERY
I create a sp that doesn't return any value and it doesn't work.
Your SP in mysql have to return a value!
for example I do this in "mysql":
CREATE DEFINER=`root`#`localhost` PROCEDURE `MyPro`(IN `Name` VARCHAR(50), IN `Id` INT, OUT `Result` INT)
MODIFIES SQL DATA
BEGIN
DECLARE Result INT;
SET Result = 0;
INSERT into MyTable (Id,Name) VALUES(Id,Name);
SELECT Result;
END
That "Id" and "Name" is input parameter and "Result" is output parameter
and create linked server in SQL SERVER and call it like this:
select * from openquery
(
Test,'call mydb.MyPro(''Name'',''16'', #P0);'
)
It works for me :D
Linked Servers and OPENQUERY, Gems to MS SQL Server...that are wolves in sheep clothing. I've found the following solutions to work when dealing with parameters
If the SP is basically just SELECT statements, the move the same to a VIEW and just pass SQL statements via OPENQUERY.
Build the OPENQUERY as a string and then use execute_sql.
You could also see if it works to precede exec with SET FMTONLY ON:
OPENQUERY([LINKSERVER],'SET FMTONLY ON; exec database.user.my_stored_proc ''AT'',''XXXX%'',''1111'',1')
If you try this and it works, you should probably Google FMTONLY+OPENQUERY to get an idea of what it means.
Try this,
SELECT * FROM OPENQUERY(linked_server_name, 'SELECT postgres_procedure_name (parameters)');
I experienced a very similar issue, but my SP wasn't taking any parameters.
I tried experimenting with altering the query sent through the openquery to include 'SET NOCOUNT ON' and 'SET FMTONLY OFF' but this had no difference.
The only solution that worked for my stored procedure was dropping the existing version, and altering the code to specifically 'SET NOCOUNT ON'
After doing this I was able to successfully run my stored proc through my linked server connection.
First of all you have to add hard code text fields then you have to
replace it by your parameters value like FromDate,TillDate,EmpID,CompCode,0,DeptID,DesgId,LocationID,AtnType
DECLARE #startdate varchar(255) = '2019-12-17'
DECLARE #enddate varchar(255) = '2019-12-17'
Set #SQL = 'SELECT * FROM OPENQUERY(' + quotename(#LinkedServer) + ',' + '''' +
'SET FMTONLY OFF; exec [TAP].[dbo].[GetAttendanceList] ' + 'FromDate,TillDate,EmpID,CompCode,0,DeptID,DesgId,LocationID,AtnType,1'')'
You have to replace your parameters values shown below
set #SQL=REPLACE(#SQL,'FromDate',+''''+''''+#startdate+''''+'''')
set #SQL=REPLACE(#SQL,'TillDate',+''''+''''+#enddate+''''+'''')
set #SQL=REPLACE(#SQL,'CompCode',+''''+''''+#CompCode+''''+'''')
set #SQL=REPLACE(#SQL,'AtnType',+''''+''''+''''+'''')
if #EmpID is Null
begin
set #SQL=REPLACE(#SQL,'EmpID','null')
end
if #DeptID is Null
begin
set #SQL=REPLACE(#SQL,'DeptID','null')
end
if #DesgId is Null
begin
set #SQL=REPLACE(#SQL,'DesgId','null')
end
if #LocationID is Null
begin
set #SQL=REPLACE(#SQL,'LocationID','null')
end
print #SQL
exec ( #SQL)