Below are my tables and I want to calculation as per formula and insert in table3 with employees.
I have 3 tables
table1 payhead master
table2 employee payheadwise salary
table3 (the destination table)
I want to calculate as per formula column and insert into table3
For example in table 2 employeid-E001 in Pay1-2000 so for Pay2 which is formula column should calculate as per pay1 value and insert into table 3 like empid-E001,payid-pay1,amount-2000 next,Empid-E001,Payid-pay2,amount-240(calculate as 2000*12/100) NextRow-Empid-E001,Payid-pay3,Amount-2240(pay1+pay2) .so as per formula it should be calculate and insert into 3rd table.
please, somebody, help me.
CREATE TABLE #Table1
(
ID VARCHAR(5),
formula VARCHAR(MAX)
)
CREATE TABLE #table2
(
employeid VARCHAR(5),
payhead VARCHAR(5),
amount MONEY
)
CREATE TABLE #table3
(
employeid VARCHAR(5),
payiD VARCHAR(5),
amount MONEY
)
INSERT INTO #Table1
VALUES ('PAY1', NULL), ('PAY2', '(PAY1+PAY2*12%)'), ('PAY3', 'PAY1 + PAY2')
INSERT INTO #Table2
VALUES ('E001', 'PAY1', 2000), ('E002', 'PAY1', 5000), ('E003', 'PAY1', 3000)
INSERT INTO #Table2
VALUES ('E001', 'PAY3', 1000), ('E002', 'PAY3', 3000), ('E003', 'PAY3', 2000)
Related
I have two tables in MS SQL:
CREATE TABLE Table1 (ID INT IDENTITY(1,1) NOT NULL, TEXTVal VARCHAR(100), Table2Id int)
insert into Table1 (TEXTVal) values('aaa');
insert into Table1 (TEXTVal) values('bbb'); insert into Table1 (TEXTVal) values('ccc');
CREATE TABLE Table2 (ID INT IDENTITY(1,1) NOT NULL, TEXTVal VARCHAR(100), Table2Id int)
Id are identity columns. I want to copy TEXTVal values from Table1 to Table2:
INSERT INTO Table2 (TEXTVal)
SELECT TEXTVal FROM Table1
where TEXTVal <> 'ccc'
and after that update column Table2Id in Table1 with appropriate values of Id from Table2. I can do this with cursor and SCOPE_IDENTITY().
I am just wondering, is there a way to do it without cursor in T-SQL?
As Jeroen stated in comments, you'll want to use OUTPUT. In the following example if you don't have an AdventureWorks database, just use a test database. You should be able to copy/paste this and just run it to see it in action!
USE AdventureWorks;
GO
----Creating the table which will store permanent table
CREATE TABLE TestTable (ID INT, TEXTVal VARCHAR(100))
----Creating temp table to store ovalues of OUTPUT clause
DECLARE #TmpTable TABLE (ID_New INT, TEXTVal_New VARCHAR(100),ID_Old INT, TEXTVal_Old VARCHAR(100))
----Insert values in real table
INSERT TestTable (ID, TEXTVal)
VALUES (1,'FirstVal')
INSERT TestTable (ID, TEXTVal)
VALUES (2,'SecondVal')
----Update the table and insert values in temp table using Output clause
UPDATE TestTable
SET TEXTVal = 'NewValue'
OUTPUT Inserted.ID, Inserted.TEXTVal, Deleted.ID, Deleted.TEXTVal INTO #TmpTable
WHERE ID IN (1,2)
----Check the values in the temp table and real table
----The values in both the tables will be same
SELECT * FROM #TmpTable
SELECT * FROM TestTable
----Clean up time
DROP TABLE TestTable
GO
ResultSet:
TmpTable:
ID_New TextVal_New ID_Old TextVal_Old
——————— ——————— ——————— ———————
1 NewValue 1 FirstVal
2 NewValue 2 SecondVal
Original Table:
ID TextVal
——————— ———————
1 NewValue
2 NewValue
As you can see it is possible to capture new values, and the values you are updating. In this example I'm just stuffing them into a table variable but you could do whatever you'd like with them. :)
I have 2 tables "#tblData1" and "#tblData2" link with "Id" column. Table "#tblData2" may or may not data for the same "Id" of "#tblData1".
Create Table #tblData1 (Id int, Details VARCHAR(10), UniqueKey VARCHAR(10), DetectDate DATE, UpdateBy VARCHAR(10));
insert into #tblData1 values (1, 'DT1', 'uq1', '01/15/2016', 'abc'), (2, 'DT2', 'uq2', '01/16/2016', 'xyz');
Create Table #tblData2 (Id int, Details VARCHAR(10), DetectDate DATE);
insert into #tblData2 values (1, 'DT11', '01/16/2016'), (1, 'DT12', '01/17/2016')
Now, I need to insert data into below 3 tables "#tblUniqueKeys", "#tblMaster" and "#tblChild".
Same Identity "MasterId" into both tables "#tblUniqueKeys" and "#tblChild".
Data from "#tblData1" into 2 tables "#tblUniqueKeys" and "#tblMaster".
Data from "#tblData2" into table ""#tblChild".
create Table #tblMaster (MasterId INT IDENTITY(101,1), Details VARCHAR(10), DetectDate DATE, UpdateBy VARCHAR(10));
create Table #tblUniqueKeys (UqId INT IDENTITY(10,1), MasterId INT, UniqueKey VARCHAR(10), DetectDate DATE);
create Table #tblChild (ChildId INT IDENTITY(201,1), MasterId INT, Details VARCHAR(10), DetectDate DATE);
Using below "Merge" sql query, I'm able to insert records into 2 table "#tblUniqueKeys" and "#tblMaster".
Question, How to insert records into the 3rd table "#tblChild"? Can we insert record into 3rd table along with "MasterId" within same Merge query? Thanks!!!
MERGE INTO #tblMaster AS Dest
USING
(
SELECT UniqueKey, Details, DetectDate, UpdateBy
FROM #tblData1
) AS Src
ON (1 = 0)
WHEN NOT MATCHED BY TARGET THEN
INSERT
(
Details
,DetectDate
,UpdateBy)
VALUES
(Src.Details
,Src.DetectDate
,Src.UpdateBy)
OUTPUT inserted.MasterId, Src.UniqueKey, Src.DetectDate
INTO #tblUniqueKeys(MasterId, UniqueKey, DetectDate);
select * from #tblMaster
select * from #tblUniqueKeys
DROP TABLE #tblData1;
drop table #tblData2;
DROP TABLE #tblMaster;
drop table #tblChild
DROP TABLE #tblUniqueKeys;
I have the following table structure:
create table table1( ID int,
assettype varchar(50));
create table t1( poolId int,
day_rate float);
create table t2( poolId int,
day_rate float);
create table lookuptable( tablename varchar(50),
assettype varchar(50));
insert into table1 values (1,'abs'), (2,'card');
insert into t1 values ( 1,5), ( 2,10);
insert into t2 values ( 1,15), ( 2,20);
insert into lookuptable values ('t1','abs'), ('t2','card');
SqlFiddle
For a given id based on the assetType field in table1 I need to perform a lookup in the lookup table so that I display if the assettype of the id is abs
poolId day_rate
1 5
2 10
else if the assettype of the id is card
poolId day_rate
1 15
2 20
The reason I have t1 and t2 tables because they have their own set of calculation and based on the asset type of the id i want to use t1 and t2
Would you be able to guide me with some query or steps to go in the right direction
I can think of the case when structure to this but in my case I have 100 entries in the lookuptable and that would mean a case when structure written for 100 times. Is there a better way of handling this?
Try this..
declare #table varchar(20)
select #table=tablename from lookuptable where assettype = 'card'
print #table
declare #query nvarchar(1000)
set #query = N'select * from [' + #table +']';
print #query
EXECUTE sp_executesql #query
Change the assettype in first query..
Are you just trying to get all the rows in table1 and then their day_rates depending on what type of asset they are? Couldn't you do something like this.
select
,table1.ID
,table1.assettype,
,(case when table1.assettype = 'abs' then t1.day_rate else t2.day_rate end) as
day_rate
from table1
inner join t1 on table1.id = t1.poolId
inner join t2 on table1.id = t2.poolId
group by table1.ID, table1.assettype
Let me identify the perspective first.
First, you created this table1 as? well whatever, but this seems a lookup table as well to me.
create table table1(
ID int,
assettype varchar(50)
);
Next, this one is a lookup table as well because this one is your reference for calculation.
create table t1(
poolId int,
day_rate float
);
create table t2(
poolId int,
day_rate float
);
Lastly, is your direct lookup table depending on the assettype defines which table you will get the rate.
create table lookuptable(
tablename varchar(50),
assettype varchar(50)
);
So, i'll try to simplify this.
One is your table1 with an additional column
create table table1(
ID int,
assettype varchar(50),
day_rate float
);
insert into table1 values
(1,'abs',5)
,(2,'card',10)
I have no further reasons yet to split the table as One-To-Many table relationship as I don't see the lookuptable as "child" as well as t1 and t2. You could instead directly change the rates in table1 rate as desired.
Please put some comments so we can arrive at the same page. thanks
create table TAB
(
id int,
Name Char(1)
);
insert into TAB(ID,NAME) values(1,'A')
insert into TAB(ID,NAME) values(1,'B')
insert into TAB(ID,NAME) values(2,'C')
insert into TAB(ID,NAME) values(2,'A')
insert into TAB(ID,NAME) values(2,'B')
insert into TAB(ID,NAME) values(3,'C')
insert into TAB(ID,NAME) values(3,'B')
this is my table and values, without using id column in where condition i need to get c,b and 3 alone from the table
Without the use of TOP / MAX or a WHERE clause :-
SET ROWCOUNT 2; -- Limit the query to just 2 rows
IF OBJECT_ID('tempdb..#tmp','U') IS NOT NULL DROP TABLE #tmp; -- Ensure #tmp table doesn't already exist
SELECT ID,Name,RANK() OVER (ORDER BY id DESC) as Rnk INTO #tmp FROM TAB
SELECT ID,Name FROM #tmp
I have two tables with foreign key constraint on TableB on TablesAs KeyA column. I was doing manual inserts till now as they were only few rows to be added. Now i need to do a bulk insert, so my question if i insert multiple rows in TableA how can i get all those identity values and insert them into TableB along with other column values. Please see the script below.
INSERT INTO Tablea
([KeyA]
,[Value] )
SELECT 4 ,'StateA'
UNION ALL
SELECT 5 ,'StateB'
UNION ALL
SELECT 6 ,'StateC'
INSERT INTO Tableb
([KeyB]
,[fKeyA] //Get value from the inserted row from TableA
,[Desc])
SELECT 1 ,4,'Value1'
UNION ALL
SELECT 2 ,5,'Value2'
UNION ALL
SELECT 3 ,6, 'Value3'
You can use the OUTPUT clause of INSERT to do this. Here is an example:
CREATE TABLE #temp (id [int] IDENTITY (1, 1) PRIMARY KEY CLUSTERED, Val int)
CREATE TABLE #new (id [int], val int)
INSERT INTO #temp (val) OUTPUT inserted.id, inserted.val INTO #new VALUES (5), (6), (7)
SELECT id, val FROM #new
DROP TABLE #new
DROP TABLE #temp
The result set returned includes the inserted IDENTITY values.
Scope identity sometimes returns incorrect value. See the use of OUTPUT in the workarounds section.