Is it possible to create a table on a linked server? - sql-server

Is it possible to create a table on a linked server?

exec
('CREATE TABLE DatabaseName.dbo.TableName
(
column1 datatype,
column2 datatype,
column3 datatype
)') at [LinkedServer]

The solution from Arpit works fine.
exec
('CREATE TABLE DatabaseName.dbo.TableName
(
column1 datatype,
column2 datatype,
column3 datatype
)') at [LinkedServer];
go
How ever, when you get the error "Msg 7411, Level 16, State 1, Line 1 Server 'MyLinkedServer' is not configured for RPC." you need to change the RPC-parameters on the linked server connection. As default RPC is set to false. It needs to be set to true.
This allows you to run procedures on the linked server.
You must allow this because the solution does not send the "Create table" statement as a SQL command to the linked server. It sends the statement as a string which in turn is executed as a procedure on the remote server.
Hope this helps.

If you're using SQL Server Management Studio and the SQLCMD mode:
-- To enable "SQLCMD mode" in SQL Server Management Studio (SSMS):
-- In the menu toolbar: Query > SQLCMD mode
:setvar LinkedServer "YourLinkedServerNameHere"
:setvar DestinationDb "YourDestinationDatabaseNameHere"
GO
EXEC ('
CREATE TABLE $(DestinationDb).dbo.YourTableNameHere (
[Field1] INT NOT NULL,
[Field2] INT NOT NULL
)
') AT $(LinkedServer)
GO
EXEC ('DROP TABLE $(DestinationDb).dbo.YourTableNameHere') AT $(LinkedServer)
GO

Related

SQL Server Invalid version: 15 (Microsoft.SqlServer.Smo)

Context: I'm having difficulty modifying a stored procedure in SQL Server 2016. The stored procedure performs parsing of json data within a file. For some reason I'm able to execute the stored procedure and it executes successfully but when I try to modify the stored procedure I get the following message:
Question: Does anyone have any troubleshooting tips? Below is the content of the stored procedure. SQL Server 2016 supports the various functions used including the OPENJSON function.
USE mattermark_sandbox
GO
CREATE PROCEDURE get_company_data
AS
IF OBJECT_ID('tempdb..##jsondump') IS NOT NULL DROP TABLE ##jsondump
IF OBJECT_ID('tempdb..##jsonparsed') IS NOT NULL DROP TABLE ##jsonparsed
IF OBJECT_ID('tempdb..##json_loop') IS NOT NULL DROP TABLE ##json_loop
CREATE TABLE ##jsondump (
[my_json] [nvarchar](max) NULL
)
-- Create a table to house the parsed content
CREATE TABLE ##jsonparsed (
[id] [int] NULL,
[url] [varchar](255) NULL,
[company_name] [varchar](255) NULL,
[domain] [varchar](255) NULL
)
-- Clear ##jsondump
TRUNCATE TABLE ##jsondump;
-- Clear ##jsonparsed ( only if you don't want to keep what's already there )
TRUNCATE TABLE ##jsonparsed;
-- Import ( single column ) JSON
--IMPORTANT: Need to be sure the company_data.json file actually exists on the remote server in that directory
BULK INSERT ##jsondump
FROM 'C:\mattermark_etl_project\company_data.json' -- ( <-- my file, point to your own )
WITH (
ROWTERMINATOR = '\n'
);
-- Select JSON into ##jsonparsed
SELECT my_json
INTO ##json_loop
FROM ##jsondump;
--SELECT * FROM ##jsondump;
INSERT INTO ##jsonparsed (
id, [url], company_name, domain
)
SELECT DISTINCT
jsn.id, jsn.[url], jsn.company_name, jsn.domain
FROM ##json_loop
OUTER APPLY (
SELECT * FROM OPENJSON(##json_loop.my_json, '$.companies' )
WITH (
id INT '$.id',
[url] VARCHAR(255) '$.url',
company_name VARCHAR(255) '$.company_name',
domain VARCHAR(255) '$.domain'
)
) AS jsn
DECLARE #bcp_cmd4 VARCHAR(1000);
DECLARE #exe_path4 VARCHAR(200) =
' cd C:\Program Files\Microsoft SQL Server\100\Tools\Binn\ & ';
SET #bcp_cmd4 = #exe_path4 +
' BCP.EXE "SELECT ''Company_ID'', ''MatterMark_URL'', ''Company_Name'', ''Domain'' UNION ALL SELECT DISTINCT cast(id as varchar( 12 )) as id, url, company_name, domain FROM ##jsonparsed" queryout ' +
' "C:\mattermark_etl_project\company_data.txt" -T -c -q -t0x7c -r\n';
PRINT #bcp_cmd4;
EXEC master..xp_cmdshell #bcp_cmd4,no_output;
SELECT DISTINCT * FROM ##jsonparsed
ORDER BY id ASC;
DROP TABLE ##jsondump
DROP TABLE ##jsonparsed
DROP TABLE ##json_loop
/*
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1;
GO
-- To update the currently configured value for advanced options.
RECONFIGURE;
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1;
GO
-- To update the currently configured value for this feature.
RECONFIGURE;
GO
*/
exec xp_cmdshell 'C:\mattermark_etl_project\powershell "C:\mattermark_etl_project\open_file.ps1"',no_output
Using SSMS version 18.0 instead of 17.0 seems to be working.
You can download it from https://learn.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-2017
You can use a query to view the stored procedure definition without installing a new SSMS.
Before running this query, you can optionally use the SSMS menu item Query -> Results To -> Results to Text to format the result in one text field.
exec sp_helptext [get_company_data]
(Where get_company_data is the stored procedure name.)
Also note that the stored procedure 'Modify' option just opens a regular query tab pre-filled with the definition as an ALTER PROCEDURE, you can instead update it by running an ALTER PROCEDURE in a normal query tab.
There is a workaround for this issue:
Instead of selecting Modify, right klick on the database name and select Tasks> Generate Scripts: Select Specific Objects, Check your object.
If you are using the Oracle server. Then use OPENQUERY. Select Syntax as follows:
select * from OPENQUERY(LINK_SERVER_NAME,'select * from DUAL')

Insert from SQL to SQLBase with linked Server

how can i insert from SQL Server to a SQLBase Database using linked Server?
Here are various examples of the correct syntax for SQLServer to SQLBase assuming your LinkedServer is called 'ISLANDLINK' . Note the two dots.
or Go here for the full script and explanation : SQLServer to SQLBase via LinkedServer
or Go here for another example: SQLServer to SQLBase via LinkedServer (more)
--Select:
SELECT * FROM OPENQUERY( ISLANDLINK, 'Select * from SYSADM.BUDGET where DEPT_ID = ''MIS'' ')
--Update:
UPDATE [ISLANDLINK]..[SYSADM].[BUDGET]
SET [BGT_YEAR] = 2016
WHERE DEPT_ID = 'MIS'
GO
--Insert:
INSERT INTO [ISLANDLINK]..[SYSADM].[EMPLOYEE]
([EMPLOYEE_ID]
,[LAST_NAME]) VALUES (99 ,'PLUMAS' )
GO
--Delete:
DELETE FROM [ISLANDLINK]..[SYSADM].[EMPLOYEE]
WHERE [LAST_NAME] = 'PLUMAS'

Parameter variable schema oracle

I'm newbie using Oracle.
I have a question: in SQL Server, we can use:
DECLARE DBNAME1 VARCHAR(20)
DECLARE DBNAME2 VARCHAR(20)
SET #DBNAME1 ='TEST_DB'
SET #DBNAME2 ='TEST_DB2'
INSERT INTO #DBNAME1.TABLECORE
SELECT *
FROM #DBNAME2.TABLENONCORE T
What is the equivalent of this script in if #DBNAME == Schema in Oracle?
We can manage it but creating db link on dbname2 :
create public database link dbname2 connect to myschema using 'abc-scan.mycompany.com.tr:1521/dbname2.mycompany.com.tr';
and calling the following dml statement from dbname1 :
insert into tablecore select * from tablenocore#dbname2;

Incorrect syntax near the keyword 'with' in stored procedure when using OPENJSON

Hi I created a stored procedure that uses OPEN JSON and insert data into a table.
The problem is when I run the stored procedure it shows an error.
I am using SQL server 2016 (SQl Server 13.0.4446.0). I am not getting the same issue when using using sql server 13.0.1742.0
CREATE PROCEDURE [dbo].Test2--'[{"FileId":1,"DataRow":"3000926900"}]'
(
#data varchar(max)
)
AS
BEGIN
create table #Temp
(
FileId bigint,
DataRow nvarchar(max),
DateLoaded DateTime
)
INSERT INTO [dbo].#Temp
SELECT * FROM OPENJSON(#data)
WITH (FileId bigint,
DataRow nvarchar(max),
DateLoaded DateTime)
select * from #temp
END
Error:
If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Check your database compatibility level. OPENJSON is new with SQL Server 2016, and if your compatibility level is set "SQL Server 2014 (120)" or less the OPENJSON function will not be correctly recognized or executed. See the MSDN docs at https://learn.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql .

INSERT INTO table RETURNING trigger-generated primary key from SQL Server linked server to Oracle (11g)

Scenario: get trigger-generated primary key when calling INSERT INTO from SQL Server linked server to Oracle
Given
Oracle 11g table with columns PRIMARY_KEY_ID, FIELD1, FIELD2, CREATE_DATE. Table has "BEFORE INSERT" trigger that selects NEXTVAL from a sequence into PRIMARY_KEY_ID field.
SQL Server 2008 R2 with Linked Server to the Oracle database containing the table above.
When I insert a record into the Oracle table, then I want to retrieve the trigger-generated primary key.
How do I do this?
Make sure these properties are set on the SQL Server linked server:
RPC=True
RPC Out=True
Execute this code in SQL Server:
DECLARE #Field1 NVARCHAR(42);
DECLARE #Field2 NVARCHAR(42);
DECLARE #PrimaryKeyValue INT;
EXECUTE (
'begin INSERT INTO MYSCHEMA.MYTABLE (
FIELD1
,FIELD2
,CREATE_DATE
)
VALUES (
?
,?
,sysdate
) RETURNING PRIMARY_KEY_ID INTO :PrimaryKeyValue; end;'
,#Field1
,#Field2
,#PrimaryKeyValue OUTPUT
) at oracle_linked_server;
Notes
begin and end; are required in the statement.
The #PrimaryKeyValue variable declared in SQL Server is the same as the :PrimaryKeyValue output parameter; Oracle uses a colon prefix for parameters.
See Calling Oracle stored procedure with output parameter from SQL Server, which provided the inspiration for this answer.

Resources