SQL Merge Statement - sql-server-2008

I am trying to use the new "MERGE" statement in SQL Server 2008. The statement will get records from a temporarty table and update the same in some other table.The statement is as following:
create table #TempTable(ProcPOAmdDel_ProcessAmendmentId bigint,ProcPOAmdDel_SemiFinProdId bigint,ProcPOAmdDel_ChallanQty int)
MERGE PurProcessPOAmendmentDelivery AS pod
USING (SELECT ProcPOAmdDel_ProcessAmendmentId,
ProcPOAmdDel_SemiFinProdId FROM #TempTable ) AS temp
ON pod.ProcPOAmdDel_ProcessAmendmentId = temp.ProcPOAmdDel_ProcessAmendmentId AND
pod.ProcPOAmdDel_SemiFinProdId=temp.ProcPOAmdDel_SemiFinProdId
WHEN MATCHED THEN UPDATE
SET pod.ProcPOAmdDel_ChallanQty = temp.ProcPOAmdDel_ChallanQty;
While running the state I encountered an error Invalid column name'ProcPOAmdDel_ChallanQty'.
Could anybody help me in resolving the issue?

Include column ProcPOAmdDel_ChallanQty in Source table i.e. temp
MERGE PurProcessPOAmendmentDelivery AS pod
USING (SELECT ProcPOAmdDel_ProcessAmendmentId,
rocPOAmdDel_SemiFinProdId,
ProcPOAmdDel_ChallanQty
FROM #TempTable ) AS temp
ON pod.ProcPOAmdDel_ProcessAmendmentId = temp.ProcPOAmdDel_ProcessAmendmentId AND
pod.ProcPOAmdDel_SemiFinProdId=temp.ProcPOAmdDel_SemiFinProdId
WHEN MATCHED THEN
UPDATE SET pod.ProcPOAmdDel_ChallanQty = temp.ProcPOAmdDel_ChallanQty;

Related

How to use IF EXISTS to check whether table exists before removing data in that table

I wanted to check whether a table exists before deleting the values inside the table. In SQL Server we can do as simple as so :
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'table_to_be_edited')
BEGIN
DELETE FROM table_to_be_edited;
END;
but how do we do it in MySQL ?
I am using MySQL Workbench V8.0.
When delete an option is to ignore the table not found error. This eliminates race conditions where a table is created between the test and the truncate. Always consider this when doing SQL operations.

SQL - delete row if another table exists

I'm trying to delete a row from a table if another table doesn't exist. I've tried using the following statement
IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'user3project3'))
BEGIN
DELETE FROM user1table WHERE id=3
END
However I get the following error:
Unrecognized statement type. (near "IF" at position 0)
I'm using phpMyAdmin with XAMPP, if that matters.
Thanks a lot in advance!
The IF statement is only allowed in programming blocks, which in practice means in stored procedures, functions, and triggers.
You could express this logic in a single query:
DELETE FROM user1table
WHERE id = 3 AND
NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'user3project3');
That said, you have a very questionable data model if you are storing a separate table for each user.

how to call stored procedure from SSIS?

I want to create a SSIS package which will call the stored procedure and dump the output of the procedure into table.
SSIS package will return the output and i need this resultset ouput to dump into another table.
But before inserting i want to update the rows from that tables if any rows exist for that date or then insert the resultset.
I do't quite understand your requirements but you could do it this way:
Drop on an execute SQL Task
Ensure that YourStagingTable exists and columns match the stored procedure output
Here is some sample code to put in your Execute SQL Task that does what you want:
-- Clear Staging Table
TRUNCATE YourStagingTable
-- Save results of stored proc into staging table
INSERT INTO YourStagingTable
EXEC YourProc
-- Update any existing records
UPDATE YourFinalTable
SET YourUpdateField = YourStagingTable.YourSourceField
FROM YourStagingTable
WHERE YourFinalTable.JoinField1 = YourStagingTable.JoinField1
-- Insert any non existing records
INSERT INTO YourFinalTable (Column1,Column2)
SELECT Column1,Column2
FROM YourStagingTable
WHERE NOT EXISTS (
SELECT 1 FROM YourFinalTable
WHERE YourFinalTable.JoinField1 = YourStagingTable.JoinField1
)

Merge statement in Sql server with target table as existing table in Sql Server 2008

QUESTION:I have table ARMS.RefRollno in my database and with roll no and rank now i have query which is returning a dataset of roll and rank .If my table contains that row then i need to update it and if not that i want to insert a new row in respect to that roll no.
create table #temp
(
ROLLNO varchar(100),
Ranking varchar(100),
TestRecID varchar(100)
)
INSERT INTO #temp (ROLLNO, Ranking,TestRecID) EXEC [ARMS].[GetStudentResultForUpdateRank] '412'
MERGE ARMS.RefRollno AS C
USING #temp AS CT
ON C.TestRecID = CT.TestRecID
WHEN MATCHED THEN
UPDATE SET
C.RefRank = CT.Ranking
WHEN NOT MATCHED THEN
INSERT (TestRecId,RefRollNo, RefRank,IsActive,CreatedDate)
VALUES (CT.TestRecID,CT.ROLLNO,CT.Ranking, 1,getdate());
drop table #temp
Here ARMS.RefRollno is my existing table in Database.
Any Help is appreciated.
** Error by Sql Server:Incorrect syntax near 'MERGE'.**
Change
EXEC [ARMS].[GetStudentResultForUpdateRank] '412'
To
EXEC [ARMS].[GetStudentResultForUpdateRank] '412';
(Note addition of trailing semicolon).
This only seems to be necessary if the database is in an earlier compatibility mode than 2008.

SSIS - Delete rows

I'm new to SSIS and need help on this one. I found an article which describes how to detect rows which exist and which have changed. The part that I'm missing is how to update rows that changed. I found some articles which say that it's also good solution to delete records which have changed and insert new recordset. The thing is I don't know how to do that step of deleting (red box).
Any suggestions?
If you have to delete the rows within Data Flow Task, then you need to use the OLE DB Command transformation and write a DELETE statement like DELETE FROM dbo.Table WHERE ColumnName = ?. Then in the column mappings of the OLE DB Command transformation, you will map the parameter represented by the question mark with the data that comes from the previous transformation. In your case, the data that comes from Union All 2.
However, I wouldn't recommend that option because OLE DB Command executes for every row and it might slow down your package if there are too many rows.
I would recommend something like this:
Redirect the output from the Union All 2 to a temporary staging table (say dbo.Staging) using OLE DB Destination.
Let's us assume that your final destination table is dbo.Destination. Now, your Staging table has all the records that should be deleted from the table Destination.
On the Control Flow tab, place an Execute SQL Task after the Data Flow Task. In the Execute SQL Task, write an SQL statement or use a stored procedure that would call an SQL statement to join the records between Staging and Destination to delete all the matching rows from Destination table.
Also, place another Execute SQL Task before the Data Flow Task. In this Execute SQL Task, delete/truncate rows from the Staging table.
Something like this might work to delete the rows:.
DELETE D
FROM dbo.Destination D
INNER JOIN dbo.Staging S
ON D.DestinationId = S.StagingId
Hope that helps.
In addition to user756519 answer. If you have millions of records to delete the last step (4) for ExecuteSQL Delete statement can be done in batches with something like this:
WHILE (1=1)
BEGIN
DELETE D
from dbo.Destination D
inner join
(
-- select ids that should be removed from table
SELECT TOP(10000) DestinationId
FROM
(
SELECT
D1.DestinationId,
S.StagingId
from
dbo.Destination as D1
LEFT JOIN
dbo.Staging as S
ON
D1.DestinationId = S.StagingId
) AS G
WHERE
StagingId IS NULL
) as R
on D.DestinationId = R.DestinationId;
IF ##ROWCOUNT < 1 BREAK
-- info message
DECLARE #timestamp VARCHAR(50)
SELECT #timestamp = CAST(getdate() AS VARCHAR)
RAISERROR ('Chunk deleted %s', 10, 1,#timestamp) WITH NOWAIT
END