Select Statement Nested Query - sql-server

I am using Zapier to add rows to SQL Server tables. However, I have needed to use the find row via custom query and create specific INSERT statements
However, Zapier will only work if there is select statement at the start of the query. The insert works but the flow fails as Zapier can only process one query / statement.
My query is
insert into Table_A (EntryID, FirstName)
output inserted.EntryID, inserted.FirstName into Table_B (EntryID, Firstname)
values (102, 'Fred')
select *
from ILR_Test
where EntryID = 102
Is there a way of making the insert activity part of a select statement through a subquery or some other way.
Thanks

Related

Multiple SQL Server inserts fail, but go unnoticed in Mule

When I run multiple insert queries together into a SQL Server database with Mule, if the second insert fails, it doesn't insert a row, and won't show as a failure in the flow or logs.
We use variables to collect together different SQL statements to insert into a header and detail table. I noticed last week that in some cases, the header record was there but no detail. There was nothing in the logs for this.
After some investigation it appears that Mule will take the result of the first SQL insert as the return code, regardless of whether the resulting SQL inserts worked or not.
I've tried changing this to a BULK UPDATE but i still get the same result.
Edit - code included for a sample insert. 4 insert statements, 3 will be successful, 1 will fail, but will simply pass back as successful -
insert into highjump.t_import_order(status,idoc_number,datetime_created,datetime_processed,error_message,wh_id,order_number,order_type,order_subtype,is_vas,is_shrinkwrap,is_mhe_packhold,is_consolidation,is_nonmhe_packhold,is_full_case,ship_to_account,ship_to_name,ship_to_address1,ship_to_address2,ship_to_address3,ship_to_city,ship_to_state,ship_to_zip,ship_to_country,sold_to_account,sold_to_name,sold_to_address1,sold_to_address2,sold_to_address3,sold_to_city,sold_to_state,sold_to_zip,telephone_number,sold_to_country,stock_pool,discount,box_type,service_level,telephone_number_alt,dest_type,carrier_code,route_code,inv_cat,cust_order_date,expected_ship_date,expected_delivery_date,dsv_tracking_number,postage_cost,carton_contents_type,unit_total,total_before_discount,total_after_discount,carton_cubing_indicator,req_proof_of_delivery,payment_type,is_cms,carrier_override_type,sales_org,pack_note_preference,shipper_order_id,master_order_number,currency_code,store_code,order_method,dsv_reference,email_address,ship_complete_flag,replen_type,carton_content_flags,partner_profile) values
(N'Z',N'0000000629673252','2019-04-12 09:57:38','2019-04-12 09:57:38',null,N'WST',N'6412210697',N'MCR',N'STD EU',0,0,0,0,0,0,N'MCRSHPTODE',N'Dave Smith',
N'888415936',N'PACKSTATION 432',null,N'Koettgenstr. 8',null,N'13629',N'DE',N'MCRSLDTODE',N'MCR SOLD TO DE',N'High St.',null,null,N'Street',null,N'BA330YA',null,
N'GB',N'MC01',0,N'BAG',N'10',null,N'RE','',N'01',N'W','2019-03-29 11:38:13','2019-03-29 11:38:13','2019-03-29 11:38:13',null,0,N'001',2,null,null,'91',1,
N'MCR CON - UK Orders',1,'1',null,N'N',null,N'623611121','GBP',null,null,null,N'Smith#arcor.com',null,'R',N'F', N'WWMULESFTH');
insert into highjump.t_import_order_cms
(order_id,delivery_from_date,delivery_to_date,pin_number,cms_location,cms_delivery_endpoint,cms_comm_preference,cms_dont_despatch_before,cms_market,cms_brand,is_gift,gift_message,loyalty_number,cms_dest_type,cms_time_delivery,cms_day_delivery,cms_customer_type,carrier_service_name,special_instructions) values ((select top(1) order_id from highjump.t_import_order where order_number='6412210697'),'2019-04-03','2019-04-03',null,N'432',N'PACKSTATIONPACKSTATION',null,null,null,N'CLA',null,null,null,N'PUDO',null,null,null,null,null);
insert into highjump.t_import_order_detail
(order_id,line_number,item_number,order_quantity,customer_item_number,ratio_pack_group,is_ratio_pack,ratio_pack_qty,uom,retail_price,freight_class,sales_order_number,customer_order_number,dsv_price_discount,customer_item_colour,price_paid,currency_code,customer_item_size)
values ((select top(1) order_id from highjump.t_import_order where order_number='6412210697'),00010,'261392464080',1.000,null,null,null,null,'U','0.0',null,N'623611121000010',N'623611121',null,null,99.95,null,null);
insert into highjump.t_import_order_detail (order_id,line_number,item_number,order_quantity,customer_item_number,ratio_pack_group,is_ratio_pack,ratio_pack_qty,uom,retail_price,freight_class,sales_order_number,customer_order_number,dsv_price_discount,customer_item_colour,price_paid,currency_code,customer_item_size)
values ((select top(1) order_id from highjump.t_import_order where order_number='6412210697'),00020,'261394324080',1.000,null,null,null,null,'U','0.0',null,N'623611121000020',N'623611121',null,null,89.95,null,null);
Structurally, these SQL queries seem to be fine. It is unclear to me why and how any of these queries would fail (or would not insert any data). It should just work fine, as far as I can see.
In the end, when you execute these queries in SQL Server Management Studio, they should all return value 1:
select count(*) from highjump.t_import_order where order_number = '6412210697';
select count(*) from highjump.t_import_order_cms where order_id = (select top (1) order_id from highjump.t_import_order where order_number = '6412210697');
select count(*) from highjump.t_import_order_detail where line_number = 10 and order_id = (select top (1) order_id from highjump.t_import_order where order_number = '6412210697');
select count(*) from highjump.t_import_order_detail where line_number = 20 and order_id = (select top (1) order_id from highjump.t_import_order where order_number = '6412210697');
Use transaction for multiple insert queries execution. In multiple SQL queries suppose one query gives error then it will be roll back.
BEGIN TRY
BEGIN TRANSACTION
//Here you will write multiple insert/delete/update queries
COMMIT
END TRY
BEGIN CATCH
ROLLBACK
END CATCH

inserted table role in instead of insert trigger

I have a view based upon 2 tables, I have written an instead of insert trigger to insert into that view:
Create trigger tr_vWEmployeeDetails_InsteadOfInsert
on vWEmployeeDetails
Instead Of Insert
as
Begin
Declare #DeptId int
Select #DeptId = DeptId
from tblDepartment
join inserted on inserted.DeptName = tblDepartment.DeptName
if(#DeptId is null)
Begin
Raiserror('Invalid Department Name. Statement terminated', 16, 1)
return
End
Insert into tblEmployee(Id, Name, Gender, DepartmentId)
Select Id, Name, Gender, #DeptId
from inserted
End
The above code works fine, but I want to know that the insert statement to the view doesn't work, instead the trigger works, then from where do we get values in the 'inserted' magic table.
Please explain.
From the relevant MSDN page:
DML trigger statements use two special tables: the deleted table and the inserted tables. SQL Server automatically creates and manages these tables. You can use these temporary, memory-resident tables to test the effects of certain data modifications and to set conditions for DML trigger actions. You cannot directly modify the data in the tables or perform data definition language (DDL) operations on the tables, such as CREATE INDEX.
The insert on the view is blocked by the use of the instead of trigger - That's literally the meaning of "instead of".
Please note that your trigger code will fail if an insert statement to the view will try to insert multiple records. The reason for this is that in SQL Server, triggers are raised per statement, and not per row. The following code that is specified in the beginning of the trigger
Declare #DeptId int
Select #DeptId = DeptId
from tblDepartment
join inserted
on inserted.DeptName = tblDepartment.DeptName
Will fail once the inserted table will have multiple rows that matches the on clause if the join.
Triggers in SQL Server must always be written to handle multiple rows in the inserted / deleted table.

Get next sequence from table in insert statement to another table

I have 3 tables
Table_A has a bunch of rows
Table_B where rows are going to be inserted with data from Table_A
Table_C holds a number (integer) called code_number
I have a stored procedure (sp_getNextCode) that selects the current code_number from Table_C, creates and returns a varchar code string with this number (like yyyyMMdd + cast(code_number as varchar) or something) and updates the Table_C code_number with the next value (code_number+1)
So far so good.
Now I want to insert a number of rows from Table_A to Table_B WITHOUT THE USE OF CURSOR
using a
INSERT INTO TABLE_B
SELECT .... FROM TABLE_A
Again so far so good
The problem is that one of the values in the above insert statement has to be the output of the stored procedure sp_getNextCode.
I cannot use the stored procedure in the statement
I cannot create a function with the same code as sp_getNextCode as the functions cannot have INSERT/UPDATE/DELETE
I don't have the option of SQL Server 2012 (which has a sequence) only SQL Server 2008
Is there any way to achieve this or the only way is with cursors (I REALLY want to avoid the cursor cause im talking about thousands of rows that need to be inserted and it takes too long )
Sure, there is a way: Create a stored procedure to read from table_A, inserts ino table_b and updates table_C:
BEGIN TRANSACTION
SELECT #last_value=last_vale FROM Table_C;
SELECT #records_to_insert = COUNT(*)
FROM Table_A
WHERE <Conditions>
INSERT INTO TABLE_A
SELECT <Fields>,...., #last_value + ROW_NUMBER()
OVER(ORDER BY <some ordering criteria>)
FROM TABLE_A
WHERE <Conditions>
UPATE Table_C
SET last_value = #last_value + #records_to_insert +1
COMMIT TRANSACTION
I am ommiting some details as the transformation of the numbers to the formatted code, exception handling and rollback, but I hope you can get the idea.
The trick is to use the ROW_NUMBER() OVER (ORDER BY...) function to obtain a unique number for each row.
http://msdn.microsoft.com/en-us/library/ms186734.aspx

How to use a select query inside an insert query in SQL Server 2005

I need to insert values into a table. But my condition is that I need to select Min(date) from another table and this value should be inserted into another table.
My query
Insert into tempTable values
('Value1','Value2','Value3',(select min(val_dt) from anotherTable),'Y',getdate())
If I use this query I am facing error.
Guide me how to use select query inside the insert query.
Instead of using VALUES() in the INSERT statement, use a SELECT to add the row values:
INSERT INTO tempTable
SELECT 'Value1', 'Value2', 'Value3', MIN(val_dt), 'Y', GETDATE()
FROM anotherTable
And the SELECT statement can be as convoluted as you want, meaning WHEREs and the like can be included.

SQL: Using an INSERT within a SELECT statement

I have a SQL SELECT statement that will create its results in XML Format. I would like to INSERT into another table (Log via insert) every time a row is selected from the original SELECT Statement. Is there anyway to include an INSERT Statement inside of a SELECT Statement?
SELECT cs_ads_StoreLocations.LocationGUID, *Bunch of Selects AS Distance
FROM *Bunch of Inter Joins*
WHERE *Bunch of conditions*
ORDER BY *You don't want to know*
FOR XML AUTO
INSERT INTO cs_ads_StoreLog (LocationGUID) VALUES (*DISTINCT cs_ads_StoreLocations.LocationGUID from select statement above*)
This is just some sample code that has the INSERT outside of the SELECT statement. I need something that has it inside the SELECT Statement or another way of running an INSERT
Just to clarify. This sample code is part of a Stored Proc
INSERT will actually accept a SELECT as its input. You can just use this command (your SELECT copied as a subquery, though you could probably refactor it to return those distinct GUIDs without a subquery...but I'd need to see the whole monster).
insert into (cs_ads_StoreLog)
select distinct
a.LocationGUID
from
(SELECT
cs_ads_StoreLocations.LocationGUID, *Bunch of Selects AS Distance
FROM
*Bunch of Inter Joins*
WHERE
*Bunch of conditions*
ORDER BY
*You don't want to know*
) a
Then, you can just return the SELECT that you have (it'll be cached, so you don't need to worry about performance hits too much).
Perhaps dynamic SQL would solve this? Example here.
Or maybe you could store the values in a table var, and do your insert on that.

Resources