How to Concatenate rows linked to single ID using group by? - postgresql

I'm writing a script to create a table that will concatenate the data from the table having the same ID. The output should be as follows: "IF DSW7841_gUDT.sOpState = 1 OR DSW7842_gUDT.sOpState = 1 OR DSW8841_gUDT.sOpState = 1 THEN GLB084.ModuleInOut.mDoorOpen := 1; ELSE GLB084.ModuleInOut.mDoorOpen := 0; END_IF;"
The script that i have written is like this:
begin
create table if not exists public.opstate_mappings (
id uuid primary key default gen_random_uuid(),
door_switch_opstate_id uuid references door_switch_opstate(id) on delete cascade,
opstate_mapping text not null unique
);
insert into opstate_mapping(door_switch_opstate_id, opstate_mapping)
select door_switch_opstate.software_instance_id,
GROUP_CONCAT('IF',door_switch_opstate.door_switches,'_gUDT.sOpState = 1 OR') AS opstate_mapping
FROM door_switch_opstate
GROUP BY software_instance_id;
end;
This is the table i am extracting data from EDIT: THIS PICTURE SHOWS ONLY ONE ID THAT IS LINKED WITH ALL THE DOOR_SWITCHES, THERE ARE OTHER MORE ID'S LINKED WITH OTHER ROWS

In Postgres the command you seek is STRING_AGG and would go something like this:
CONCAT('IF ',
STRING_AGG(door_switch_opstate.door_switches, '_gUDT.sOpState = 1 OR'),
'_gUDT.sOpState = 1 THEN GLB084.ModuleInOut.mDoorOpen := 1; ELSE GLB084.ModuleInOut.mDoorOpen := 0; END_IF;'
)

Related

ColdFusion 2016 and stored proc throwing invalid character error

I am trying existing code in a CF 2016 install... I get this error
"[Macromedia][DB2 JDBC Driver][DB2]ILLEGAL SYMBOL =; VALID SYMBOLS ARE ..."
the line identified is a param of a stored proc call that looks like this:
<cfstoredproc datasource="#application.dsn#" procedure="LIVE.STOPS">
<cfprocparam type="In" cfsqltype="CF_SQL_BIGINT" dbvarname="STOPID" value="#val( variables.procstopid )#" null="no">
<cfprocparam type="In" cfsqltype="CF_SQL_INTEGER" dbvarname="TRIPID" value="#val( url.tripId )#" null="no">
</cfstoredproc>
I cannot find any mention on line of a change in stored proc tag - maybe the DB2 driver? I'm looking for any input. Thanks.
Other info;
Windows10, Apache2.4, connectiong to DB2 v10.
#pendo, Here is the stored proc - it should be noted that I abbreviated some of the sql, but the SP works and has for a long time in the app running CF10.
CREATE OR REPLACE PROCEDURE LIVE.STOP(
IN stopId BIGINT DEFAULT 0,
IN tripId INTEGER DEFAULT 0
) LANGUAGE SQL
BEGIN
DECLARE updateTripId INTEGER DEFAULT 0;
DECLARE minStopId BIGINT DEFAULT 0;
DECLARE maxStopId BIGINT DEFAULT 0;
DECLARE TripSearch_cursor CURSOR FOR
SELECT s1.fkTripsId
FROM live.paymentsTripsStops s1
JOIN live.Trips t ON s1.fkTripsId = t.Id
WHERE s1.fkStopsId = stopId
FETCH FIRST 1 ROWS ONLY;
DECLARE minMaxStop_cursor CURSOR FOR
SELECT
COALESCE(
(
SELECT s.Id
FROM live.Stops s
JOIN live.Trips t ON s.fkTripsId = t.Id
ORDER BY s.Sequence
FETCH FIRST 1 ROWS ONLY
),
0
) AS firstStopId,
COALESCE(
(
SELECT s.Id
FROM live.Stops s
JOIN live.Trips t ON s.fkTripsId = t.Id
ORDER BY s.Sequence DESC
FETCH FIRST 1 ROWS ONLY
),
0
) AS lastStopId
FROM live.Trips t
WHERE t.Id = updateTripId
FETCH FIRST 1 ROWS ONLY;
IF TripId > 0
THEN SET updateTripId = TripId;
ELSE OPEN TripSearch_cursor;
FETCH FROM TripSearch_cursor INTO updateTripId;
CLOSE TripSearch_cursor;
END IF;
IF updateTripId > 0
THEN OPEN minMaxStop_cursor;
FETCH FROM minMaxStop_cursor INTO minStopId, maxStopId;
CLOSE minMaxStop_cursor;
UPDATE live.Trips
SET fkFirstStopId = minStopId,
fkLastStopId = maxStopId
WHERE intId = updateTripId;
END IF;
END

Firebird dynamic Var New and Old

I need validate dynamic Fields from a Table. For example:
CREATE TRIGGER BU_TPROYECTOS FOR TPROYECTOS
BEFORE UPDATE AS
DECLARE VARIABLE vCAMPO VARCHAR(64);
BEGIN
/*In then table "TCAMPOS" are the fields to validate*/
for Select CAMPO from TCAMPOS where TABLA = TPROYECTOS and ACTUALIZA = 'V' into :vCAMPO do
Begin
if (New.:vCAMPO <> Old.:vCampo) then
/*How i get dynamic New.Field1, New.Field2 on query return*/
End;
END ;
The question is : How can I put "The name of the field that the query returns me " in the above code .
Ie if the query returns me the field1 and field5 , I would put the trigger
if ( New.Field1 < > Old.Field1 ) or ( New.Field5 < > Old.Field5 ) then
There is no such feature in Firebird. You will need to create (and preferably) generate triggers that will reference all fields hard coded. If the underlying table changes or the requirements for validation, you will need to recreate the trigger to take the added or removed fields into account.

Cannot insert NULL value into column error

I have a issue where I want to update a column in a table and with a trigger to update same column but in another table. It says I cannot insert NULL but I can't seem to understand from where it gets that NULL value. This is the trigger:
CREATE TRIGGER Custom_WF_Update_WF_DefinitionSteps_DefinitionId ON WF.Definition
AFTER UPDATE AS BEGIN
IF UPDATE(DefinitionId)
IF TRIGGER_NESTLEVEL() < 2
BEGIN
ALTER TABLE WF.DefinitionSteps NOCHECK CONSTRAINT ALL
UPDATE WF.DefinitionSteps
SET DefinitionId =
(SELECT i.DefinitionId
FROM inserted i,
deleted d
WHERE WF.DefinitionSteps.DefinitionId = d.DefinitionId
AND i.oldPkCol = d.DefinitionId)
WHERE WF.DefinitionSteps.DefinitionId IN
(SELECT DefinitionId FROM deleted)
ALTER TABLE WF.DefinitionSteps CHECK CONSTRAINT ALL
END
END
This update statement works just fine:
UPDATE [CCHMergeIntermediate].[WF].[Definition]
SET DefinitionId = source.DefinitionId + 445
FROM [CCHMergeIntermediate].[WF].[Definition] source
But this one fails:
UPDATE [CCHMergeIntermediate].[WF].[Definition]
SET DefinitionId = target.DefinitionId
FROM [CCHMergeIntermediate].[WF].[Definition] source
INNER JOIN [centralq3].[WF].[Definition] target
ON (((source.Name = target.Name) OR (source.Name IS NULL AND target.Name IS NULL)))
I get the following error:
Msg 515, Level 16, State 2, Procedure Custom_WF_Update_WF_DefinitionSteps_DefinitionId, Line 7
Cannot insert the value NULL into column 'DefinitionId', table 'CCHMergeIntermediate.WF.DefinitionSteps'; column does not allow nulls. UPDATE fails.
If I do a select instead of the update statement, like this:
SELECT source.DefinitionId, target.DefinitionId
FROM [CCHMergeIntermediate].[WF].[Definition] source
INNER JOIN [centralq3].[WF].[Definition] target
ON (((source.Name = target.Name) OR (source.Name IS NULL AND target.Name IS NULL)))
I get this result:
http://i.stack.imgur.com/3cZsM.png (sorry for external link, I don't have enaugh reputation to post image here )
What am I doing wrong? What I don't see? What am I missing..?
The problem was in the trigger at the condition. I modified the second where from i.oldPkCol = d.DefinitionId to i.oldPkCol = **d.oldPkCol** and it worked.
UPDATE WF.DefinitionSteps
SET DefinitionId =
(SELECT i.DefinitionId
FROM inserted i,
deleted d
WHERE WF.DefinitionSteps.DefinitionId = d.DefinitionId
AND i.oldPkCol = **d.oldPkCol**)
WHERE WF.DefinitionSteps.DefinitionId IN
(SELECT DefinitionId FROM deleted)

How to set a bit based on a value existing in a table

I have a table. I have 2 variables, one is a bit, the other is an int.
Table: WorkGroupCollectionDetail
Variables: #WorkgroupID int, #IsFSBP bit
The table has WorkGroupId int PK and WorkGroupCollectionCode varchar PK. That's it.
I can run a query like this:
SELECT WorkGroupId
FROM WorkGroupCollectionDetail
WHERE WorkGroupCollectionCode = 'FSBP'
and it gives me a list of WorkGroupID.
So what I need to do is if the value of #WorkgroupID is inside the results of that query, I need to set the bit variable to true.
select #IsFBSP = case
when exists (
select 42 from WorkGroupDetailCollection
where WorkGroupCollectionCode = 'FSBP' and WorkGroupId = #WorkGroupId ) then 1
else 0 end
which is logically equivalent to:
select #IsFBSP = case
when #WorkGroupId in (
select WorkGroupId from WorkGroupDetailCollection
where WorkGroupCollectionCode = 'FSBP' ) then 1
else 0 end
A query using EXISTS often performs better than a query using IN. You can check the execution plans to see how they compare in your particular case.
Note that these examples include setting the bit value to zero as well as one.
You could modify the SELECT to include the check for the WorkGroupId and update the #IsFSBP accordingly:
IF EXISTS(SELECT WorkGroupId
FROM WorkGroupCollectionDetail
WHERE WorkGroupCollectionCode = 'FSBP'
AND WorkGroupId = #WorkgroupID)
BEGIN
SELECT #IsFSBP = 1;
END
SQL Fiddle example
I'm guessing you're looking for
Set #BitVariable = count(*)
From TestTable
WHERE TestCode = 'TestValue' and TestID = #TestID

Metadata about a column in SQL Server 2008 R2?

I'm trying to figure out a way to store metadata about a column without repeating myself.
I'm currently working on a generic dimension loading SSIS package that will handle all my dimensions. It currently does :
Create a temporary table identical to the given table name in parameters (this is a generic stored procedure that receive the table name as parameter, and then do : select top 0 * into ##[INSERT ORIGINAL TABLE NAME HERE] from [INSERT ORIGINAL TABLE NAME HERE]).
==> Here we insert custom code for this particular dimension that will first query the data from a datasource and get my delta, then transform the data and finally loads it into my temporary table.
Merge the temporary table into my original table with a T-SQL MERGE, taking care of type1 and type2 fields accordingly.
My problem right now is that I have to maintain a table with all the fields in it to store a metadata to tell my scripts if this particular field is type1 or type2... this is nonsense, I can get the same data (minus type1/type2) from sys.columns/sys.types.
I was ultimately thinking about renaming my fields to include their type in it, such as :
FirstName_T2, LastName_T2, Sex_T1 (well, I know this can be type2, let's not fall into that debate here).
What do you guyz would do with that? My solution (using a table with that metadata) is currently in place and working, but it's obvious that repeating myself from the systables to a custom table is nonsense, just for a simple type1/type2 info.
UPDATE: I also thought about creating user defined types like varchar => t1_varchar, t2_varchar, etc. This sounds like something a bit sluggy too...
Everything you need should already be in INFORMATION_SCHEMA.COLUMNS
I can't follow your thinking of not using provided tables/views...
Edit: As scarpacci mentioned, this somewhat portable if needed.
I know this is bad, but I will post an answer to my own question... Thanks to GBN for the help tho!
I am now storing "flags" in the "description" field of my columns. I, for example, can store a flag this way : "TYPE_2_DATA".
Then, I use this query to get the flag back for each and every column :
select columns.name as [column_name]
,types.name as [type_name]
,extended_properties.value as [column_flags]
from sys.columns
inner join sys.types
on columns.system_type_id = types.system_type_id
left join sys.extended_properties
on extended_properties.major_id = columns.object_id
and extended_properties.minor_id = columns.column_id
and extended_properties.name = 'MS_Description'
where object_id = ( select id from sys.sysobjects where name = 'DimDivision' )
and is_identity = 0
order by column_id
Now I can store metadata about columns without having to create a separate table. I use what's already in place and I don't repeat myself. I'm not sure this is the best possible solution yet, but it works and is far better than duplicating information.
In the future, I will be able to use this field to store more metadata, where as : "TYPE_2_DATA|ANOTHER_FLAG|ETC|OH BOY!".
UPDATE :
I now store the information in separate extended properties. You can manage extended properties using sp_addextendedproperty and sp_updateextendedproperty stored procedures. I have created a simple store procedure that help me to update those values regardless if they currently exist or not :
create procedure [dbo].[UpdateSCDType]
#tablename nvarchar(50),
#fieldname nvarchar(50),
#scdtype char(1),
#dbschema nvarchar(25) = 'dbo'
as
begin
declare #already_exists int;
if ( #scdtype = '1' or #scdtype = '2' )
begin
select #already_exists = count(1)
from sys.columns
inner join sys.extended_properties
on extended_properties.major_id = columns.object_id
and extended_properties.minor_id = columns.column_id
and extended_properties.name = 'ScdType'
where object_id = (select sysobjects.id from sys.sysobjects where sysobjects.name = #tablename)
and columns.name = #fieldname
if ( #already_exists = 0 )
begin
exec sys.sp_addextendedproperty
#name = N'Scd_Type',
#value = #scdtype,
#level0type = N'SCHEMA',
#level0name = #dbschema,
#level1type = N'TABLE',
#level1name = #tablename,
#level2type = N'COLUMN',
#level2name = #fieldname
end
else
begin
exec sys.sp_updateextendedproperty
#name = N'Scd_Type',
#value = #scdtype,
#level0type = N'SCHEMA',
#level0name = #dbschema,
#level1type = N'TABLE',
#level1name = #tablename,
#level2type = N'COLUMN',
#level2name = #fieldname
end
end
end
Thanks again