How to run multiple queries in one instance in SQL Server 2005 - sql-server

I want to run a SELECT statement and I want execute a DELETE statement for the same row and the read result be respond by the SQL Server.

WITH cte AS (
SELECT *
FROM <mytable>
WHERE key = <mykey>)
DELETE cte
OUTPUT deleted.*;
There are many ways to skin this cat. I often preffer the one posted because is very readable. It clearly separates the SELECT into its own query expression, allowing for easily created complex queries. It deletes exactly the query result. It outputs the deleted rows.
The following is also perfectly valid and easier for simple WHERE clauses:
DELETE <mytable>
OUTPUT deleted.*
WHERE key = <mykey>;

Related

How can prevent a SQL Server merge using OUTPUT from updating the target table

I know how to update a target table from a source table using a SQL server MERGE statement.
I know I can capture the changes using an OUTPUT statement.
Problem: When using output statement to capture the changes they are still applied to the target table.
Question: How can I prevent the MERGE statement from updating the target and only capture the output?
Extra info: The goal in this case is not to audit, which is the common OUTPUT statement use in MERGE. The goal is to determine the changes and then do further processing on them that cannot be added to the merge. You could also call it doing a Dry-Run.
In order for MERGE to emit anything as part of the OUTPUT clause, it would have to perform an UPDATE or INSERT.
Off the top of my head, I can see two means to accomplish what you want:
One:
Write some SQL to capture the data set that feeds into the MERGE statement and use it to figure out what the MERGE would do. I know I didn't explain that very well so here's an example with pseudo-code.
SELECT
s.*
,d.PrimaryKey
INTO
#SourceForMerge
FROM
[Source] AS s
LEFT OUTER JOIN [Destination] AS d
ON s.MatchingColumnA = d.MatchingColumnA
AND s.MatchingColumnB = d.MatchingColumnB
;MERGE [Destination] AS d
USING
(
SELECT * FROM #SourceForMerge
) AS s
ON
d.PrimaryKey = s.PrimaryKey
WHEN MATCHED THEN
-- UPDATE columns
WHEN NOT MATCHED THEN
-- INSERT columns
OUTPUT
-- columns
INTO
#OutputTempTable
This would allow you to interrogate the #SourceForMerge temp table to see what matched and what didn't.
Alternatively, you could be an outlaw and wrap the MERGE in a transaction, capture the OUTPUT, SELECT it somewhere and then deliberately ROLLBACK to "undo" the changes.
This strikes me as the most accurate method but also a little scary.
When I'm testing some SQL, I'll often do this by wrapping something in a TRANSACTION and then having something like:
SELECT 1 / 0
to trigger a ROLLBACK.

ORACLE to MSSQL using SSMS Import Wizard with Query to Update Rows

I have a situation which prevent me of updating rows in a table in MSSQL getting the data from ORACLE. I can INSERT fine from ORACLE to MS SQL using a SELECT statement like:
SELECT XRECORDACTIVATIONDATE, XRECORDCUTOFFDATE, XRECORDREVIEWDATE,
XRECORDFILINGDATE, XNOLATESTREVISIONDATE, XNEWREVISIONDATE, XDATERECEIVEDDOC,
XINACTIVEDATE, DCREATEDATE, DINDATE, DRELEASEDATE, DLASTMODIFIEDDATE
FROM STELLENT.V_EXPORT_TO_MSSQL V
But when I try to update the rows based on an unique ID using:
UPDATE D
SET D.XRECORDACTIVATIONDATE = V.XRECORDACTIVATIONDATE
FROM DBO.DOCUMENT D
INNER JOIN STELLENT."V_EXPORT_TO_MSSQL" V ON D.DID = V.DID
I get the following error:
ORA-00933: SQL command not properly ended
(System.Data.OracleClient)
DBO.DOCUMENT is a MSSQL table.
STELLENT.V_EXPORT_TO_MSSQL is a View in ORACLE
I might be writing wrong the query I will appreciate some help. thank you.
Lukasz is correct - a select statement is a lot different from an insert statement.
The ORA-00933 error means your query is not formed properly. This is because in Oracle, the database expects queries to follow a certain format/standard. Typically, queries within Oracle will have a form of SELECT [columns] FROM [tables] WHERE [conditions]. This can vary - for example if you wanted to select all data from a table, that query might look like "SELECT * FROM [table];" and the WHERE clause can be omitted because you do not need to define a condition for the database to return all rows. While queries can vary in form, in general, they will follow some type of format.
You are receiving this error because your query does not conform to the expected form, and it is because you have an INNER JOIN that directly follows your FROM clause. To fix this, I would recommend creating a query that you use to select the records you want to update, and then using that select statement to form your update statement by replacing the "SELECT" with "UPDATE".
For more on SQL Standards and how to format your queries, I would recommend taking a look at Oracle documentation. https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_1001.htm#SQLRF52344

How to create a "Ghost Table" in SQL Server based off of other tables?

I need to create a "ghost" table in SQL Server, which doesn't actually exist but is a result set of a SQL Query. Pseudo code is below:
SELECT genTbl_col1, genTblcol2
FROM genTbl;
However, "genTbl" is actually:
SELECT table1.col AS genTbl_col1,
table2.col AS genTbl_col2
FROM table1 INNER JOIN table2 ON (...)
In other words, I need that every time a query is run on the server trying to select from "genTbl", it simply creates a result set from the query and treats it like a real table.
The situation is that I have a software that runs queries on a database. I need to modify it, but I cannot change the software itself, so I need to trick it into thinking it can actually query "genTbl", when it actually doesn't exist but is simply a query of other tables.
To clarify, the query would have to be a sort of procedure, available by default in the database (i.e. every time there is a query for "genTbl").
Use #TMP
SELECT genTbl_col1, genTblcol2
INTO #TMP FROM genTbl;
It exists only in current session. You can also use ##TMP for all sessions.

Single field in select statement returning two columns

So I'm running a query like so:
select col1 from table_name
and it's returning me two columns:
Server Name | col1
I've not run into this before. I'm sure it's surprisingly simple, but it's surprisingly hard to search for online. Any way I can JUST get col1 back?
In SSMS you can select to run a query against multiple servers/databases at once. When you do that each result has an additional column added with the server name. That is most likely what is going on here. Close the query window, open a new one and make sure you directly connect to the server in question. That should remove that column.
More info: http://msdn.microsoft.com/en-us/library/bb964743.aspx

error when insert into linked server

I want to insert some data on the local server into a remote server, and used the following sql:
select * into linkservername.mydbname.dbo.test from localdbname.dbo.test
But it throws the following error
The object name 'linkservername.mydbname.dbo.test' contains more than the maximum number of prefixes. The maximum is 2.
How can I do that?
I don't think the new table created with the INTO clause supports 4 part names.
You would need to create the table first, then use INSERT..SELECT to populate it.
(See note in Arguments section on MSDN: reference)
The SELECT...INTO [new_table_name] statement supports a maximum of 2 prefixes: [database].[schema].[table]
NOTE: it is more performant to pull the data across the link using SELECT INTO vs. pushing it across using INSERT INTO:
SELECT INTO is minimally logged.
SELECT INTO does not implicitly start a distributed transaction, typically.
I say typically, in point #2, because in most scenarios a distributed transaction is not created implicitly when using SELECT INTO. If a profiler trace tells you SQL Server is still implicitly creating a distributed transaction, you can SELECT INTO a temp table first, to prevent the implicit distributed transaction, then move the data into your target table from the temp table.
Push vs. Pull Example
In this example we are copying data from [server_a] to [server_b] across a link. This example assumes query execution is possible from both servers:
Push
Instead of connecting to [server_a] and pushing the data to [server_b]:
INSERT INTO [server_b].[database].[schema].[table]
SELECT * FROM [database].[schema].[table]
Pull
Connect to [server_b] and pull the data from [server_a]:
SELECT * INTO [database].[schema].[table]
FROM [server_a].[database].[schema].[table]
I've been struggling with this for the last hour.
I now realise that using the syntax
SELECT orderid, orderdate, empid, custid
INTO [linkedserver].[database].[dbo].[table]
FROM Sales.Orders;
does not work with linked servers. You have to go onto your linked server and manually create the table first, then use the following syntax:
INSERT INTO [linkedserver].[database].[dbo].[table]
SELECT orderid, orderdate, empid, custid
FROM Sales.Orders
WHERE shipcountry = 'UK';
I've experienced the same issue and I've performed the following workaround:
If you are able to log on to remote server where you want to insert data with MSSQL or sqlcmd and rebuild your query vice-versa:
so from:
SELECT * INTO linkservername.mydbname.dbo.test
FROM localdbname.dbo.test
to the following:
SELECT * INTO localdbname.dbo.test
FROM linkservername.mydbname.dbo.test
In my situation it works well.
#2Toad: For sure INSERT INTO is better / more efficient. However for small queries and quick operation SELECT * INTO is more flexible because it creates the table on-the-fly and insert your data immediately, whereas INSERT INTO requires creating a table (auto-ident options and so on) before you carry out your insert operation.
I may be late to the party, but this was the first post I saw when I searched for the 4 part table name insert issue to a linked server. After reading this and a few more posts, I was able to accomplish this by using EXEC with the "AT" argument (for SQL2008+) so that the query is run from the linked server. For example, I had to insert 4M records to a pseudo-temp table on another server, and doing an INSERT-SELECT FROM statement took 10+ minutes. But changing it to the following SELECT-INTO statement, which allows the 4 part table name in the FROM clause, does it in mere seconds (less than 10 seconds in my case).
EXEC ('USE MyDatabase;
BEGIN TRY DROP TABLE TempID3 END TRY BEGIN CATCH END CATCH;
SELECT Field1, Field2, Field3
INTO TempID3
FROM SourceServer.SourceDatabase.dbo.SourceTable;') AT [DestinationServer]
GO
The query is run on DestinationServer, changes to right database, ensures the table does not already exist, and selects from the SourceServer. Minimally logged, and no fuss. This information may already out there somewhere, but I hope it helps anyone searching for similar issues.

Resources