I'm trying the following
Insert number of records to table A with a table-valued parameter (tvp). This tvp has extra column(s) that are not in A
Get the inserted ids from A and the corresponding extra columns in the the tvp and add them to another table B
Here's what I tried
Type:
CREATE TYPE tvp AS TABLE
(
id int,
otherid int,
name nvarchar(50),
age int
);
Tables:
CREATE TABLE A (
[id_A] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50),
[age] [int]
);
CREATE TABLE B (
[id_B] [int] IDENTITY(1,1) NOT NULL,
[id_A] [int],
[otherid] [int]
);
Insert:
DECLARE #a1 AS tvp;
DECLARE #a2 AS tvp
-- create a tvp (dummy data here - will be passed to as a param to an SP)
INSERT INTO #a1 (name, age, otherid) VALUES ('yy', 10, 99999), ('bb', 20, 88888);
INSERT INTO A (name, age)
OUTPUT
inserted.id_A,
inserted.name,
inserted.age,
a.otherid -- <== isn't accepted here
INTO #a2 (id, name, age, otherid)
SELECT name, age FROM #a1 a;
INSERT INTO B (id_A, otherid) SELECT id, otherid FROM #a2
However, this fails with The multi-part identifier "a.otherid" could not be bound., which I guess is expected because columns from other tables are not accepted for INSERT statement (https://msdn.microsoft.com/en-au/library/ms177564.aspx).
from_table_name
Is a column prefix that specifies a table included in the FROM clause of a DELETE, UPDATE, or MERGE statement that is used to specify the rows to update or delete.
So is there any other way to achieve this?
You cannot select value from a source table by using INTO operator.
Use OUTPUT clause in the MERGE command for such cases.
DECLARE #a1 AS tvp;
DECLARE #a2 AS tvp
INSERT INTO #a1 (name, age, otherid) VALUES ('yy', 10, 99999), ('bb', 20, 88888);
MERGE A a
USING #a1 a1
ON a1.id =a.[id_A]
WHEN NOT MATCHED THEN
INSERT (name, age)
VALUES (a1.name, a1.age)
OUTPUT inserted.id_A,
a1.otherId,
inserted.name,
inserted.age
INTO #a2;
INSERT INTO B (id_A, otherid) SELECT id, otherid FROM #a2
Two tables are defined below. Names are arranged in a parent-child relationship. how to Show a nested (tree) list of names including [Id], [Name] and [Level], where [Level] indicates the nest level from the top (Root: Level = 0; First children of Root: Level = 1; etc…).
CREATE TABLE [Names]
(
[Id] INT PRIMARY KEY,
[Name] VARCHAR(100)
)
CREATE TABLE [Relationships]
(
[Parent] [int] REFERENCES [Names]([Id]),
[Child] [int] REFERENCES [Names]([Id])
)
INSERT [NAMES] VALUES (1,'FRANK')
INSERT [NAMES] VALUES (2,'JO')
INSERT [NAMES] VALUES (3,'MARY')
INSERT [NAMES] VALUES (4,'PETER')
INSERT [NAMES] VALUES (5,'MAY')
INSERT [RELATIONSHIPS] VALUES (1,0)
INSERT [RELATIONSHIPS] VALUES (2,1)
INSERT [RELATIONSHIPS] VALUES (3,2)
INSERT [RELATIONSHIPS] VALUES (4,1)
INSERT [RELATIONSHIPS] VALUES (5,2)
I am using ms sql server 2008
I think this is sweet and simple way
SELECT child AS ID , N.Name , ISNULL(R.Parent, 0) AS Lavel
FROM Relationships R ,NAMES N
WHERE R.Child = N.Id ORDER BY parent,child
ID Name Level
1 FRANK 0
2 JO 1
4 PETER 1
3 MARY 2
5 MAY 2
common table expressions allow you to do recursive calls for things like this. Search for that. It will go something like this:
with cte as (
select *, 1 as lvl
from relationships as a
join names as b ...
union
select *, lvl + 1
from ....
)
select * from cte;
I may not have it exactly right, but searching for cte recursion will help.
Use Recursive CTE to do this.
;WITH cte
AS (SELECT NAME,
Parent,
Child,
0 AS level
FROM [Names] N
JOIN Relationships r
ON r.Parent = n.Id
WHERE Child IS NULL
UNION ALL
SELECT b.NAME,
b.Parent,
b.Child,
level + 1
FROM cte a
JOIN (SELECT NAME,
Parent,
Child
FROM [Names] N
JOIN Relationships r
ON r.Parent = n.Id) b
ON a.Parent = b.Child)
SELECT * FROM cte
Note : In Relationship table first row (ie) INSERT [RELATIONSHIPS] VALUES (1,0) you cannot insert 0 in child column since Names table does not have such entry.
If it is the root then then you can use NULL instead of 0 like INSERT [RELATIONSHIPS] VALUES (1,null)
CREATE TABLE [Names]
(
[Id] INT PRIMARY KEY,
[Name] VARCHAR(100)
)
CREATE TABLE [Relationships]
(
[Child] [int] REFERENCES [Names]([Id]),
[Parent] [int] REFERENCES [Names]([Id])
)
INSERT [NAMES] VALUES (1,'FRANK')
INSERT [NAMES] VALUES (2,'JO')
INSERT [NAMES] VALUES (3,'MARY')
INSERT [NAMES] VALUES (4,'PETER')
INSERT [NAMES] VALUES (5,'MAY')
INSERT [RELATIONSHIPS] VALUES (1,Null)
INSERT [RELATIONSHIPS] VALUES (2,1)
INSERT [RELATIONSHIPS] VALUES (3,2)
INSERT [RELATIONSHIPS] VALUES (4,1)
INSERT [RELATIONSHIPS] VALUES (5,4)
--first have a look at INSERT [RELATIONSHIPS] VALUES (1,0), you are
--saying 0 is the child of 1. I think you need to swap the column
--names? - this solution assumes you meant parent to be child
--and visa-versa - i.e. I swapped them above
--second, do you need the relationships table? cant you just have a
--reports_to column in the names table?
--third, you cant have a value of 0 in either column of your relationships
--table because of the FK constraint to names - no name exists
--with id = 0, insert NULL instead
--fourth, I changed May's manager so that it was clear that lvl & manager werent related
;with
cte as
(select id, name, isnull(parent,0) as manager
from Names n
left join Relationships r
on r.child = n.id),
r_cte as
(select 0 as lvl, id, name, manager
from cte
where manager = 0
union all
select r.lvl + 1, c.id, c.Name, c.manager
from cte c
inner join r_cte r
on c.manager = r.id
)
select * from r_cte
Let me describe the whole situation: I have below two tables. The values of MaxTestCasesExecutedBySingleUser and TotalTestCasesExecutedByAllUser in Module table needs to be updated using some Aggregate clause
CREATE TABLE [dbo].[Module](
[ProjectID] [int] NOT NULL,
[ModuleID] [int] NOT NULL,
[ModuleName] [nvarchar](100) NOT NULL,
[MaxTestCasesExecutedBySingleUser] [int] NULL,
[TotalTestCasesExecutedByAllUser] [int] NULL,
PRIMARY KEY ([ProjectID],[ModuleID]))
CREATE TABLE [dbo].[ModuleMember](
[ProjectID] [int] NOT NULL,
[ModuleID] [int] NOT NULL,
[SerialNo] [int] NOT NULL,
[Name] [nvarchar](100) NOT NULL,
PRIMARY KEY ([ProjectID],[ModuleID],[SerialNo]))
Insert Into Module Values (1,1,'Installation_Test',null,null)
Insert Into Module Values (1,2,'Server_Test',null,null)
Insert Into Module Values (1,3,'Client_Test',null,null)
Insert Into Module Values (1,4,'Security_Test',null,null)
Insert Into ModuleMember Values(1,1,0,'Jim')
Insert Into ModuleMember Values(1,1,1,'Bob')
Insert Into ModuleMember Values(1,2,0,'Jack')
Insert Into ModuleMember Values(1,2,1,'Steve')
Insert Into ModuleMember Values(1,2,2,'Roy')
Insert Into ModuleMember Values(1,2,3,'Jerry')
Insert Into ModuleMember Values(1,3,0,'Root')
Insert Into ModuleMember Values(1,3,1,'Tom')
Insert Into ModuleMember Values(1,4,0,'Evil')
There is another Table Valued Function dbo.GetValue which takes Name (from ModuleMember table) as parameter and returns the values of Name and TestCasesExecutedByTheUser in the form of a table. I need to update these two values in Module table.
Definition:
MaxTestCasesExecutedBySingleUser = maximum number if test case executed by a member in a module
TotalTestCasesExecutedByAllUser = total number of test cases executed by all member in a module.
I tried below query but it is throwing me error : An aggregate may not appear in the set list of an UPDATE statement.
UPDATE M
SET
M.MaxTestCasesExecutedBySingleUser = MAX(N.TestCasesExecutedByTheUser),
M.TotalTestCasesExecutedByAllUser = SUM(N.TestCasesExecutedByTheUser)
FROM Module M
JOIN ModuleMember Mem ON (M.ProjectID = Mem.ProjectID AND M.ModuleID = Mem.ModuleID)
CROSS APPLY dbo.GetValue(Mem.Name) N
The workaround is a little more verbose - you have to get the aggregates first (e.g. in a CTE), and then update the target table:
;WITH src AS
(
SELECT
Mem.ProjectID,
Mem.ModuleID,
mtc = MAX(N.TestCasesExecutedByTheUser),
stc = SUM(N.TestCasesExecutedByTheUser)
FROM dbo.ModuleMember AS Mem
CROSS APPLY dbo.GetValue(Mem.Name) AS N
GROUP BY Mem.ProjectID, Mem.ModuleID
)
UPDATE M
SET M.MaxTestCasesExecutedBySingleUser = src.mtc,
M.TotalTestCasesExecutedBySingleUser = src.stc
FROM dbo.Module AS M
INNER JOIN src
ON M.ProjectID = src.ProjectID
AND M.ModuleID = src.ModuleID;
I think it's perfect case to use apply
update Module set
MaxTestCasesExecutedBySingleUser = C.maxtc,
TotalTestCasesExecutedByAllUser = C.sumtc
from Module as M
cross apply (
select
max(N.TestCasesExecutedByTheUser) as maxtc,
sum(N.TestCasesExecutedByTheUser) as sumtc
from ModuleMember as MM
cross apply dbo.GetValue(MM.Name) as N
where MM.ProjectID = M.ProjectID and MM.ModuleID = M.ModuleID
) as C
Here is my scenario:
I have a Person table with following fields.
create table Person(PersonID int primary key identity(1,1),
Age int,
height decimal(4,2),
weight decimal(6,2)
);
insert into Person(Age,height,weight) values (60,6.2,169); -- 1
insert into Person(Age,height,weight) values (15,5.1,100); -- 2
insert into Person(Age,height,weight) values (10,4.5,50); -- 3
What I need to do is,
if the person Age >= 18 and height >= 6 then calculationValue = 20
if the person Age >= 18 and height < 6 then calculationValue = 15
if the person Age < 18 and weight >= 60 then calculationValue = 10
if the person Age < 18 and weight < 60 then calculationValue = 5
based on these condition I need to find the calculationValue and do some math.
I tried to make a flexible model so in future it would be easier to add any more conditions and can easily change the constant values (like 18, 6, 60 etc)
I created couple of tables as below:
create table condTable(condTableID int primary key identity(1,1),
condCol varchar(20),
startValue int,
endValue int
);
insert into condTable(condCol,startValue,endValue) values ('Age',18,999) -- 1
insert into condTable(condCol,startValue,endValue) values ('Height',6,99) -- 2
insert into condTable(condCol,startValue,endValue) values ('Height',0,5.99) -- 3
insert into condTable(condCol,startValue,endValue) values ('Age',0,17) -- 4
insert into condTable(condCol,startValue,endValue) values ('Weight',60,999) -- 5
insert into condTable(condCol,startValue,endValue) values ('Weight',0,59) -- 6
I join two condition to make it one in the following table as given by the requirement.(ie. if age >=18 and height >=6 then calculationValue = 20. etc)
create table CondJoin(CondJoin int,condTableID int,CalculationValue int)
insert into CondJoin values (1,1,20)
insert into CondJoin values (1,2,20)
insert into CondJoin values (2,1,15)
insert into CondJoin values (2,3,15)
insert into CondJoin values (3,4,10)
insert into CondJoin values (3,5,10)
insert into CondJoin values (4,4,5)
insert into CondJoin values (4,6,5)
I think this model will provide the flexibility of adding more conditions in future. But I am having difficulties on implementing it in SQL Server 2005. Anyone can write a sql that process in set basis and compare the value in Person table with CondJoin table and provide the corresponding calculationvalue. For eg. for person ID 1 it should look at CondJoin table and give the calculationValue 20 since his age is greater than 18 and height is greater than 6.
this looks like you are headed towards dynamic sql generation.
i think maybe you would be better off with a row for each column and cutoff values for the ranges, and a value if true ... maybe something like:
age_condition
-----------------
min_age
max_age
value
this is something that you could populate and then query without some dynamic generation.
The following is extremely rough but it should get the point across. It normalizes the data and moves towards a semi-object oriented (attribute/value/attribute value) structure. I'll leave it up to you to reinforce referential integrity, but the following is flexible and will return the results you want:
CREATE TABLE Person (
PersonID INT PRIMARY KEY IDENTITY(1,1)
,Name NVARCHAR(255)
);
GO
CREATE TABLE PersonAttribute (
PersonID INT
,CondAttributeID INT
,Value NVARCHAR(255)
);
GO
CREATE TABLE CondAttribute (
AttributeID INT PRIMARY KEY IDENTITY(1,1)
,Attribute NVARCHAR(255));
GO
CREATE TABLE CondTable (
CondTableID INT PRIMARY KEY IDENTITY(1,1)
,CondAttributeID INT
,StartValue MONEY
,EndValue MONEY
);
GO
CREATE TABLE CalculationValues (
CalculationID INT PRIMARY KEY IDENTITY(1,1)
,CalculationValue INT
);
GO
CREATE TABLE CondCalculation (
CondTableID INT
,CalculationID INT
);
INSERT Person (Name)
VALUES ('Joe')
,('Bob')
,('Tom');
INSERT PersonAttribute (
PersonID
,CondAttributeID
,Value
)
VALUES (1, 1, '60')
,(1, 2, '6.2')
,(1, 3, '169')
,(2, 1, '15')
,(2, 2, '5.1')
,(2, 3, '100')
,(3, 1, '10')
,(3, 2, '4.5')
,(3, 3, '50');
INSERT CondAttribute (Attribute)
VALUES ('Age')
,('height')
,('weight');
INSERT CondTable (
CondAttributeID
,StartValue
,EndValue)
VALUES (1,18,999) --Age
,(2,6,99) --Height
,(2,0,5.99) -- Height
,(1,0,17) -- Age
,(3,60,999) -- Weight
,(3,0,59); -- Weight
INSERT CalculationValues (CalculationValue)
VALUES (5)
,(10)
,(15)
,(20);
INSERT CondCalculation (CondTableID, CalculationID)
VALUES (1,4)
,(2,4)
,(1,3)
,(3,3)
,(4,2)
,(5,2)
,(5,1)
,(6,1);
SELECT *
FROM Person AS p
JOIN PersonAttribute AS pa ON p.PersonID = pa.PersonID
JOIN CondAttribute AS ca ON pa.CondAttributeID = ca.AttributeID
JOIN CondTable AS ct ON ca.AttributeID = ct.CondAttributeID
AND CONVERT(money,pa.Value) BETWEEN ct.StartValue AND ct.EndValue
JOIN CondCalculation AS cc ON cc.CondTableID = ct.CondTableID
JOIN CalculationValues AS c ON cc.CalculationID = c.CalculationID
WHERE p.PersonID = 1
The following solution uses PIVOT (twice) to transform the combination of CondJoin and condTable into a chart, then joins the chart to the Person table to calculate the target value. I believe, a series of CASE expressions could be used instead just as well. Anyway...
All the tables have been turned into table variables, for easier testing. So first, DDL and data preparation:
declare #Person table(PersonID int primary key identity(1,1),
Age int,
height decimal(4,2),
weight decimal(6,2)
);
insert into #Person(Age,height,weight) values (60,6.2,169); -- 1
insert into #Person(Age,height,weight) values (15,5.1,100); -- 2
insert into #Person(Age,height,weight) values (10,4.5,50); -- 3
declare #condTable table(condTableID int primary key identity(1,1),
condCol varchar(20),
startValue int,
endValue int
);
insert into #condTable(condCol,startValue,endValue) values ('Age',18,999) -- 1
insert into #condTable(condCol,startValue,endValue) values ('Height',6,99) -- 2
insert into #condTable(condCol,startValue,endValue) values ('Height',0,5.99) -- 3
insert into #condTable(condCol,startValue,endValue) values ('Age',0,17) -- 4
insert into #condTable(condCol,startValue,endValue) values ('Weight',60,999) -- 5
insert into #condTable(condCol,startValue,endValue) values ('Weight',0,59) -- 6
declare #CondJoin table(CondJoin int,condTableID int,CalculationValue int);
insert into #CondJoin values (1,1,20)
insert into #CondJoin values (1,2,20)
insert into #CondJoin values (2,1,15)
insert into #CondJoin values (2,3,15)
insert into #CondJoin values (3,4,10)
insert into #CondJoin values (3,5,10)
insert into #CondJoin values (4,4,5)
insert into #CondJoin values (4,6,5)
And now the query:
;with startValues as (
select
CondJoin,
Age,
Height,
Weight,
CalculationValue
from (
select
j.CondJoin,
j.CalculationValue,
t.condCol,
t.startValue
from #CondJoin j
inner join #condTable t on j.condTableID = t.condTableID
) j
pivot (
max(startValue) for condCol in (Age, Height, Weight)
) p
),
endValues as (
select
CondJoin,
Age,
Height,
Weight,
CalculationValue
from (
select
j.CondJoin,
j.CalculationValue,
t.condCol,
t.endValue
from #CondJoin j
inner join #condTable t on j.condTableID = t.condTableID
) j
pivot (
max(endValue) for condCol in (Age, Height, Weight)
) p
),
combinedChart as (
select
s.CondJoin,
AgeFrom = s.Age,
AgeTo = e.Age,
HeightFrom = s.Height,
HeightTo = e.Height,
WeightFrom = s.Weight,
WeightTo = e.Weight,
s.CalculationValue
from startValues s
inner join endValues e on s.CondJoin = e.CondJoin
)
select
p.*,
c.CalculationValue
from #Person p
left join combinedChart c
on (c.AgeFrom is null or p.Age between c.AgeFrom and c.AgeTo)
and (c.HeightFrom is null or p.Height between c.HeightFrom and c.HeightTo)
and (c.WeightFrom is null or p.Weight between c.WeightFrom and c.WeightTo)
In the data below I am looking for a query so I can join the results of the 2 tables by nearest neighbor.
Some of the results in dbo.Interests Table will not be in the dbo.Details Table,
This Question finds the k nearest poins for a single point, I need this query to further reconcile data between the 2 tables
How can I extend this SQL query to find the k nearest neighbors?
IF OBJECT_ID('dbo.Interests', 'U') IS NOT NULL DROP TABLE dbo.Interests;
IF OBJECT_ID('dbo.Details', 'U') IS NOT NULL DROP TABLE dbo.Details;
CREATE TABLE [dbo].[Interests](
[ID] [int] IDENTITY(1,1) NOT NULL,
[NAME] [nvarchar](255) NULL,
[geo] [geography] NULL,
)
CREATE TABLE [dbo].[Details](
[ID] [int] IDENTITY(1,1) NOT NULL,
[NAME] [nvarchar](255) NULL,
[geo] [geography] NULL,
)
/*** Sample Data ***/
/* Interests */
INSERT INTO dbo.Interests (Name,geo) VALUES ('Balto the Sled Dog',geography::STGeomFromText('POINT(-73.97101284538104 40.769975451779729)', 4326));
INSERT INTO dbo.Interests (Name,geo) VALUES ('Albert Bertel Thorvaldsen',geography::STGeomFromText('POINT(-73.955996808113582 40.788611756916609)', 4326));
INSERT INTO dbo.Interests (Name,geo) VALUES ('Alice in Wonderland',geography::STGeomFromText('POINT(-73.966714294355356 40.7748020248959)', 4326));
INSERT INTO dbo.Interests (Name,geo) VALUES ('Hans Christian Andersen',geography::STGeomFromText('POINT(-73.96756141015176 40.774416211045626)', 4326));
/* Details */
INSERT INTO dbo.Details(Name,geo) VALUES ('Alexander Hamilton',geography::STGeomFromText('POINT(-73.9645616688172 40.7810234271951)', 4326));
INSERT INTO dbo.Details(Name,geo) VALUES ('Arthur Brisbane',geography::STGeomFromText('POINT(-73.953249720745731 40.791599412827864)', 4326));
INSERT INTO dbo.Details(Name,geo) VALUES ('Hans Christian Andersen',geography::STGeomFromText('POINT(-73.9675614098224 40.7744162102582)', 4326));
INSERT INTO dbo.Details(Name,geo) VALUES ('Balto',geography::STGeomFromText('POINT(-73.9710128455336 40.7699754516397)', 4326));
A brute force approach will be to compute the distance between all details X interests records:
SELECT *
FROM
(
SELECT *, rank=dense_rank() over (partition by IName, IGeo order by dist asc)
FROM
(
SELECT D.NAME as DName, D.geo as DGeo,
I.NAME as IName, I.geo as IGeo,
I.geo.STDistance(D.geo) AS dist
FROM dbo.Details D CROSS JOIN dbo.Interests I
) X
) Y
WHERE rank <= #k
NotE: #k is the target number of matches you are after