Let's say I have two tables, table-a and table-b.
Table-a has the following columns: product_id, mission_id, mission_status, mission_source, mission_destinition.
Table-b has two columns: product_id, location_id.
If I were to write a stored procedure which removes a row from table-a where mission_status=1, and then automatically create a new row in table-b consisting of the product_id and mission_destination from the row just removed in table-a, how would I write the stored procedure?
There are a few different ways to accomplish this. As someone said above, a trigger may be the way to go. Here's a simple script that might work in this case.
--Create test tables
CREATE TABLE #TEMP1
(
product_id int,
mission_Id int,
mission_status int,
mission_source int,
mission_destination VARCHAR(50)
);
CREATE TABLE #TEMP2
(
product_id int,
location_id VARCHAR(50)
);
--Test data
INSERT INTO #TEMP1
VALUES(1,1,1,2,'Mars')
INSERT INTO #TEMP1
VALUES(2,1,1,2,'Jupiter')
INSERT INTO #TEMP1
VALUES(3,1,1,2,'Venus')
INSERT INTO #TEMP1
VALUES(4,1,1,2,'Saturn')
--Check for mission_status of 1
SELECT product_id, mission_destination FROM #TEMP1 WHERE mission_status = 1
IF ##ROWCOUNT > 0
BEGIN
INSERT INTO #TEMP2 (product_id,location_id) SELECT product_id, mission_destination FROM #TEMP1 WHERE mission_status = 1
DELETE FROM #TEMP1 WHERE mission_status = 1
END
SELECT * FROM #TEMP1
SELECT * FROM #TEMP2
Related
I have 2 table first is master table second is transaction table.i want to insert data from second table into temp table .
I need to insert a table data from another table. I trying to write this sql code. But this order by option is not working while inserting the data
insert data from table in order of grant table .but i think it insert fist then order.
here is my table syntax.
Create table tabl_master
(DESC_ID int IDENTITY(1,1) PRIMARY KEY,
SUM_DESCRIPTION nvarchar(500)
)
Create table tabl1
(PROGRESS_REPORT_BUDGETID int IDENTITY(1,1) PRIMARY KEY,
RFP_ID int,
DESC_ID int ,
TOTAL_BUDGET decimal(18,2)
)
insert into tabl_master values('1.1 Salaries-Program management staff')
insert into tabl_master values('1.2 Salaries-Field staff, outreach workers, medical staff and other service providers')
insert into tabl_master values('1.3 Other HR Costs')
insert into tabl_master values('1.4 Salaries-Finance and Administration Staff')
insert into tabl_master values('2.2 Technical Assistance related per diems/transport/other costs')
insert into tabl_master values('2.3 Assistance related per diems/transport/other costs')
insert into tabl1 values(101,1,2500)
insert into tabl1 values(101,2,7500)
insert into tabl1 values(101,3,3500)
insert into tabl1 values(101,4,0)
insert into tabl1 values(101,5,0)
insert into tabl1 values(101,6,0)
insert into tabl1 values(101,7,0)
DECLARE #ProductTotals TABLE
(
srnum int,
PROGRESS_REPORT_BUDGETID int,
SUM_DESCRIPTION nvarchar(550),
RFP_ID int,
DESC_ID int,
GRAND_TOTAL decimal(18,3)
)
insert into #ProductTotals
SELECT row_number() over (order by (select NULL))as srnum,
PROGRESS_REPORT_BUDGETID,BS.SUM_DESCRIPTION,
RFP_ID, PB.DESC_ID, TOTAL_BUDGET
FROM tabl1 PB
INNER JOIN tabl_master BS ON PB.DESC_ID=BS.DESC_ID
ORDER BY TOTAL_BUDGET desc
select * from #ProductTotals
Result is coming as
enter image description here
And i am expecting result as
enter image description here
DECLARE #ProductTotals TABLE
(
srnum int,
PROGRESS_REPORT_BUDGETID int,
SUM_DESCRIPTION nvarchar(550),
RFP_ID int,
DESC_ID int,
GRAND_TOTAL decimal(18,3)
)
insert into #ProductTotals
SELECT row_number() over (order by (select NULL))as srnum,
PROGRESS_REPORT_BUDGETID,SUM_DESCRIPTION,
RFP_ID, DESC_ID, TOTAL_BUDGET from(
SELECT
PROGRESS_REPORT_BUDGETID,BS.SUM_DESCRIPTION,
RFP_ID, PB.DESC_ID, TOTAL_BUDGET
FROM tabl1 PB
INNER JOIN tabl_master BS ON PB.DESC_ID=BS.DESC_ID
where TOTAL_BUDGET <> 0
union all
select PROGRESS_REPORT_BUDGETID,BS.SUM_DESCRIPTION,
RFP_ID, PB.DESC_ID, TOTAL_BUDGET
FROM tabl1 PB
INNER JOIN tabl_master BS ON PB.DESC_ID=BS.DESC_ID
where TOTAL_BUDGET = 0
) A
select * from #ProductTotals
and my expected answer will be like this
enter image description here
Table structre
table 1
account
123
1234
12345
123456
table 2
account
123
1234
12345
I want to return table a record 123456 on account for table1 and null for column 2 when it doesnt match table 2
SQL
SELECT table1.account, table2.account
from table1
left outer join table2
on (table1.account= table2.account)
Your where statement explicitly asked for non-null rows with table2.dates = '19-jul-17'
You should modify your query to check for nulls:
SELECT
table1.account, table2.account
from table1
left outer join table2
on (table1.account= table2.account)
where
t1.dates='20170719'
and ( table2.account is NULL
or
table2.dates = '20170719'
)
This matches rows that have a specific date in the first table, and either null or a specific date on the second.
Note the date literal. The original query used a locale-specific format. This can fail easily faile in locales that don't use that format. Never mind the two digit year.
YYYYMMDD on the other hand is unambiguous.
UPDATE
Once the where clause is removed, NULLs are returned as expected :
declare #table1 table (id int)
declare #table2 table (id int)
insert into #table1
values
(123 ),
(1234 ),
(12345 ),
(123456)
insert into #table2
values
(123 ),
(1234 ),
(12345)
SELECT t1.id, t2.id
from #table1 t1
left outer join #table2 t2
on (t1.id= t2.id)
Returns
id id
123 123
1234 1234
12345 12345
123456 NULL
If the question is "how do I get the non-matching row" the answer is use WHERE tabl2.ID IS NULL
Everything is OK in your query, If you are using any where clause, please remove and check, BTW i am not able to reproduce your issue. PFB attempt, The query gives expected result
create table #tmp1( ID int)
create table #tmp2( ID int)
Insert into #tmp1 values('123')
Insert into #tmp1 values ('1234')
Insert into #tmp1 values ('12345')
Insert into #tmp1 values ('123456')
Insert into #tmp2 values('123')
Insert into #tmp2 values ('1234')
Insert into #tmp2 values ('12345')
select * from #tmp1
select * from #tmp2
SELECT #tmp1.ID, #tmp2.ID from #tmp1 left outer join #tmp2 on (#tmp1.ID=#tmp2.ID)
drop table #tmp1
drop table #tmp2
The result is:
ID ID
123 123
1234 1234
12345 12345
123456 NULL
I would like to merge two tables without common columns in MSSQL while keep all the rows in each table as separate row in the merged table.
Scenario:
Table A Col1 Col2
1 1.Col1 1.Col2
2 2.Col1 2.Col2
Table B Col3
3 3.Col3
Here is what i expected:
Table Col1 Col2 Col3
1 1.Col1 1.Col2 Null
2 2.Col1 2.Col2 Null
3 Null Null 3.Col3
Simply use Union and select NULL for other columns to avoid:
All queries combined using a UNION, INTERSECT or EXCEPT operator must
have an equal number of expressions in their target lists.
Demo:-
Create table #Table1 ( A int, Col1 varchar (10), Col2 varchar(10))
Create table #Table2 ( b int, Col3 varchar (10))
insert into #Table1 values (1,'1.Col1',' 1.Col2')
insert into #Table1 values (2,'2.Col1','2.Col2')
insert into #Table2 values (3,'3.Col3')
select A,Col1,Col2,null as Col3 from #Table1
union
select B,null,null,Col3 from #Table2
go
drop table #Table1
go
drop table #Table2
Result:-
Select A,Col1,Col2,null as Col3 from tblA Union All Select B,null ,null ,Col3 from tblB
My table has these columns:
int ID (Is Identity)
BusinessFilterPhrase nvarchar(50)
BusinessCategoryID int
Want to insert one record 'been' and 4 only if there not exists a record with 'been'. The statement below insert multiple records depend on how many record that do not have 'been'. So if my table have no record with data 'been' and there are 3 records in the table, it will insert 3 records with the new data 'been' and 4. I'm confused.
insert into tblBusinessName(BusinessFilterPhrase, BusinessCategoryID)
select 'been', 4
from tblBusinessName t1
where NOT EXISTS (select 1
from tblBusinessName d1
where d1.BusinessFilterPhrase = 'been'
)
It seem inserting top 1 into the first select work. Any other way to do this without making BuisnessFilterPhrase Unique in the table?
insert into tblBusinessName(BusinessFilterPhrase, BusinessCategoryID)
select top 1 'been', 4
from tblBusinessName t1
where NOT EXISTS (select 1
from tblBusinessName d1
where d1.BusinessFilterPhrase = 'been'
)
Just found out this statement will not insert anything if your table is blank. Note select top 1.
Just don't select from the table at all:
insert into tblBusinessName(BusinessFilterPhrase, BusinessCategoryID)
select 'been', 4
where not exists (select * from tblBusinessName where BusinessFilterPhrase = 'been')
Or alternatively:
if not exists (select * from tblBusinessName where BusinessFilterPhrase = 'been')
begin
insert into tblBusinessName(BusinessFilterPhrase, BusinessCategoryID)
select 'been', 4
end
I am writing a stored procedure to get a list of records from TableA and insert those records into TableB. now i'm facing issue in this.
Here is my sp :
USE [Sample_DB]
GO
SET ANSI_NULLS ON
GOenter code here
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[AddStoredProcedure]
AS
BEGIN
DECLARE #ProcessedData AS TABLE (Name varchar(200),MaritalStatus varchar(200))
INSERT INTO #ProcessedData (Name ,MaritalStatus )
SELECT Name,MaritalStatus from TableA where MaritalStatus='Male'
INSERT INTO [TableB]
(
Id
,Name
,MaritalStatus
)
SELECT ('M_'+cast(RIGHT(Year(getDate()),2) as varchar)+'_'+cast(REPLACE(STR((select MAX(Id)+1 from [TableA] where MaritalStatus='Male'),4),' ','0') as varchar)),Name,MaritalStatus FROM #ProcessedData
END
TableA contains,
Id Name MaritalStatus
1 John Male
2 Sam Male
3 Seema Female
when i execute the stored procedure, AddStoredProcedure
I'm getting the output as
TableB contains,
Id Name MaritalStatus
M_13_0003 John Male
M_13_0003 Sam Male
But i need as below;
TableB should be,
Id Name MaritalStatus
M_13_0003 John Male
M_13_0004 Sam Male
Thank you all in advance for your response.
You can use row_number function as:
DECLARE #ProcessedData AS TABLE (Name varchar(200),MaritalStatus varchar(200))
INSERT INTO #ProcessedData (Name ,MaritalStatus )
SELECT Name,MaritalStatus from TableA where MaritalStatus='Male'
DECLARE #IdMax int;
SELECT #IdMax = MAX(Id)
FROM [TableA]
WHERE MaritalStatus='Male';
INSERT INTO [TableB]
(
Id
,Name
,MaritalStatus
)
SELECT ('M_'+cast(RIGHT(Year(getDate()),2) as varchar)+'_'+cast(REPLACE(STR((row_number() over(Order by Name)+#IdMax ),4),' ','0') as varchar)),
Name,MaritalStatus
FROM #ProcessedData
DECLARE #TableA TABLE (Id INT, Name VARCHAR(20), MaritalStatus VARCHAR(6))
DECLARE #TableB TABLE (Id VARCHAR(9), Name VARCHAR(20), MaritalStatus VARCHAR(6))
INSERT INTO #TableA (Id, Name, MaritalStatus)
VALUES
(1, 'John', 'Male'),
(2, 'Sam', 'Male'),
(3, 'Seema', 'Female')
DECLARE #ProcessedData AS TABLE (Id INT IDENTITY(1,1), Name varchar(200),MaritalStatus varchar(200))
INSERT INTO #ProcessedData (Name ,MaritalStatus )
SELECT Name
,MaritalStatus
FROM #TableA
WHERE MaritalStatus='Male'
INSERT INTO #TableB (Id, Name, MaritalStatus)
SELECT ('M_'+cast(RIGHT(Year(getDate()),2) as varchar)+'_'+cast(REPLACE(STR((select MAX(Id) from #TableA where MaritalStatus='Male')+Id,4),' ','0') as varchar))
,Name
,MaritalStatus
FROM #ProcessedData
SELECT * FROM #TableB
I've replaced your tables with table variables so it runs straight off the bat.
Is there any reason you want to start from 0003? This query will produce your desired output anyway, comment if you need changes.