I am still getting a weird error:
The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns.
Code:
INSERT INTO @tab (Phone)
select t2.Phone
from
(
SELECT DISTINCT top 999 t3.Phone, MIN(t3.Ord)
FROM
(
select Phone1 as Phone, Ord from @tabTemp
union all
select Phone2 as Phone, Ord from @tabTemp
) t3
GROUP BY t3.Phone
ORDER BY MIN(t3.Ord) asc, t3.Phone
) t2
The idea is to select all phone numbers from @tabTemp with their row order. Then I wanna distinct them and insert distincted numbers into table @tab. Top 999 is here only for order by purpose, because I use it into a function (UDF).
Structures are following:
declare @tabTemp TABLE
(
Phone1 varchar(128) NULL,
Phone2 varchar(128) NULL,
Ord int
);
declate @tab TABLE
(
Phone varchar(max) NULL
);
EDITED:
FULL CODE
CREATE FUNCTION dbo.myFnc(@PID int, @VID int, @JID int, @ColumnNo int)
RETURNS @tab TABLE
(
Phone varchar(max) NULL
)
AS
BEGIN
if @PID is null and @VID is null and @JID is null
return;
if @ColumnNo is null or (@ColumnNo<>2 and @ColumnNo<>3 and @ColumnNo<>6)
return;
declare @catH int;
set @catH = dbo.fncGetCategoryID('H','tt'); -- just returning int value
declare @kvalP int;
set @kvalP = dbo.fncGetCategoryID('P','te');
declare @kvalR int;
set @kvalR = dbo.fncGetCategoryID('R','te');
declare @tabTemp TABLE
(
Phone1 varchar(128) NULL,
Phone2 varchar(128) NULL,
Ord int
);
-- finding parent subject + current one
WITH subj AS(
SELECT *
FROM Subjekt
WHERE
(ID = @PID and @PID is not null)
or
(ID = @VID and @VID is not null)
or
(ID = @JID and @JID is not null)
UNION ALL
SELECT t.*
FROM Subjekt t
INNER JOIN subj r ON r.ID = t.ID
)
INSERT INTO @tabTemp (Phone1,Phone2)
(select
(case when o.TYP1=@catH then o.TEL1 else null end) Phone1
,(case when o.TYP2=@catH then o.TEL2 else null end) Phone2
,so.POR_C
from
subj s
,SubjektPerson so
,Persons o
,recSetup idS
,recSetup idSO
,recSetup idO
where 1=1
and idO.isValid=1
and idSO.isValid=1
and idS.isValid=1
and idSO.ID0=so.ID
and idS.ID0=s.ID
and idO.ID0=o.ID
and so.ID_PERSON=o.ID
and so.ID_SUBJECT=s.ID
and (o.TYP=@kvalP or o.TYP=@kvalR)
)
INSERT INTO @tab (Phone)
select t2.Phone
from
(
SELECT DISTINCT top 999 t3.Phone, MIN(t3.Ord)
FROM
(
select Phone1 as Phone, Ord from @tabTemp
union all
select Phone2 as Phone, Ord from @tabTemp
) t3
GROUP BY t3.Phone
ORDER BY MIN(t3.Ord) asc, t3.Phone
) t2
RETURN
END
You've focussed on the wrong insert. This is the one with the mismatch:
INSERT INTO @tabTemp (Phone1,Phone2)
(select
(case when o.TYP1=@catH then o.TEL1 else null end) Phone1
,(case when o.TYP2=@catH then o.TEL2 else null end) Phone2
,so.POR_C
from
...
Two columns in the insert list, 3 columns in the subselect. I can't tell just from the naming whether POR_C
was meant to end up in the Ord
column or not.