Produce XML from MS SQL, structure issues, namespace prefix: - sql-server

I'm trying to run SQL for complex XML out of MS SQL Server 2016. I made a huge progress considering that I'm new to XML generation but still can't figure out how to do that nesting portion to make Export/Client structure matter what I tried putting into nested ROOT clause. Not sure if this issue also causing that I'm missing hmis: prefix for most Elements. I need them like on attached picture with Desired output/schema.
Also pasting self containing test Input and working code , I marked with ???? places which I think caused this trouble. Appreciate your hints. Do you think it's will be easy to do with other types FOR XML ? Explicit ???
Best Mario
SQL Version: Microsoft SQL Server 2017 (RTM-CU27)
Updated: added #export table
/* --- test data/table
DROP TABLE IF EXISTS #t;
SELECT * INTO #T FROM ( -- SELECT * FROM #T
SELECT 111 PersonalID, 'Alpha' first_name, 'Brown' last_name, '1/1/2000' birth_date, 'Manager Alpha' CaseManager_PH, 0 Female, '3/2/2022' ExportDate, 'AW3' user_updated UNION
SELECT 222 PersonalID, 'Bobby' , 'Dow' , '2/2/2002', 'Manager2222' , 0 , '3/3/2022' ExportDate, 'BBX3' ) A
SELECT * FROM #T
*/
DECLARE #export TABLE (
ExportDate date , StartDate DATE, EndDate date)
INSERT INTO #export (ExportDate, StartDate, EndDate)
VALUES ('3/22/2022', '1/1/2022', '4/4/2022')
; WITH XMLNAMESPACES ('https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd' as hmis,
'http://www.w3.org/2001/XMLSchema-instance' AS xsi )
SELECT
10 AS [hmis:SourceID],
111 AS [hmis:Export/ExportID]
,CAST(e.ExportDate AS VARCHAR(10)) AS [hmis:Export/ExportDate] ---<<< Change
,CAST(e.StartDate AS VARCHAR(10)) AS [hmis:Export/ExportPeriod/StartDate]
,CAST(e.EndDate AS VARCHAR(10)) AS [hmis:Export/ExportPeriod/EndDate]
, (
SELECT
ExportDate AS [hmis:Client/#DateCreated], ExportDate AS [hmis:Client/#dateUpdated],
PersonalID AS [hmis:Client/PersonalID],
first_name AS [hmis:Client/first_name],
last_name AS [hmis:Client/last_name],
birth_date AS [hmis:Client/birth_date],
CaseManager_PH AS [hmis:Client/CustomClientElements/CaseManager_PH],
'Unknown' AS [hmis:Client/CustomClientElements/Casemanager_ContactInfo],
user_updated AS [hmis:Client/user_updated]
FROM #t t
-- WHERE 1=1
FOR XML path , ROOT('Export'), TYPE) ---????
FROM #export e
FOR XML PATH('Source'), ROOT('Sources')
Desired output format:
<hmis:Sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:hmis="https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd">
<hmis:Source>
<hmis:SourceID>10</hmis:SourceID>
<hmis:Export>
<ExportID>111</ExportID>
<ExportDate>2022-03-22</ExportDate>
<ExportPeriod>
<StartDate>2022-01-01</StartDate>
<EndDate>2022-04-04</EndDate>
</ExportPeriod>
<hmis:Client DateCreated="3/2/2022" DateUpdated="3/2/2022">
<hmis:PersonalID>111</hmis:PersonalID>
<hmis:first_name>Alpha</hmis:first_name>
<hmis:last_name>Brown</hmis:last_name>
<hmis:birth_date>1/1/2000</hmis:birth_date>
<hmis:CustomClientElements>
<hmis:CaseManager_PH>Manager Alpha</hmis:CaseManager_PH>
<hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo>
</hmis:CustomClientElements>
<hmis:user_updated>AW3</hmis:user_updated>
</hmis:Client>
<hmis:Client DateCreated="3/3/2022" DateUpdated="3/3/2022">
<hmis:PersonalID>222</hmis:PersonalID>
<hmis:first_name>Bobby</hmis:first_name>
<hmis:last_name>Dow</hmis:last_name>
<hmis:birth_date>2/2/2002</hmis:birth_date>
<hmis:CustomClientElements>
<hmis:CaseManager_PH>Manager2222</hmis:CaseManager_PH>
<hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo>
</hmis:CustomClientElements>
<hmis:user_updated>BBX3</hmis:user_updated>
</hmis:Client>
</hmis:Export>
</hmis:Source>
</hmis:Sources>

Please try the following solution.
The desired output is produced in two steps:
Raw XML via FOR XML PATH('r'), TYPE, ROOT('root').
Fine tuned final XML via XQuery .query() method and FLWOR expression.
Because a minimal reproducible example is not provided, I hope I didn't miss anything.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (
PersonalID INT PRIMARY KEY,
first_name VARCHAR(30),
last_name VARCHAR(30),
birth_date DATE,
CaseManager_PH VARCHAR(30),
Female BIT,
ExportDate DATE,
user_updated VARCHAR(30)
);
INSERT INTO #tbl (
PersonalID,
first_name,
last_name,
birth_date,
CaseManager_PH,
Female,
ExportDate,
user_updated
)
VALUES
(111, 'Alpha', 'Brown', '2000-01-01', 'Manager Alpha', 0, '2022-03-02', 'AW3'),
(222, 'Bobby', 'Dow', '2002-02-02', 'Manager2222', 0 , '2022-03-03', 'BBX3');
DECLARE #export TABLE (ExportDate date , StartDate DATE, EndDate date);
INSERT INTO #export (ExportDate, StartDate, EndDate) VALUES
('2022-03-22', '2022-01-01', '2022-04-04');
-- DDL and sample data population, end
DECLARE #ExportDate date, #StartDate DATE, #EndDate DATE;
SELECT #ExportDate = ExportDate, #StartDate = StartDate, #EndDate = EndDate
FROM #export;
WITH XMLNAMESPACES ('https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd' as hmis,
'http://www.w3.org/2001/XMLSchema-instance' AS xsi )
SELECT (
SELECT * FROM #tbl
FOR XML PATH('r'), TYPE, ROOT('root'))
.query('<hmis:Sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<hmis:Source>
<hmis:SourceID>10</hmis:SourceID>
<hmis:Export>
<ExportID>111</ExportID>
<ExportDate>{sql:variable("#ExportDate")}</ExportDate>
<ExportPeriod>
<StartDate>{sql:variable("#StartDate")}</StartDate>
<EndDate>{sql:variable("#EndDate")}</EndDate>
</ExportPeriod>
{
for $x in /root/r
return <hmis:Client DateCreated="{$x/ExportDate}" DateUpdated="{$x/ExportDate}">
<hmis:PersonalID>{data($x/PersonalID)}</hmis:PersonalID>
<hmis:first_name>{data($x/first_name)}</hmis:first_name>
<hmis:last_name>{data($x/last_name)}</hmis:last_name>
<hmis:birth_date>{data($x/birth_date)}</hmis:birth_date>
<hmis:CustomClientElements>
<hmis:CaseManager_PH>{data($x/CaseManager_PH)}</hmis:CaseManager_PH>
<hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo>
</hmis:CustomClientElements>
<hmis:user_updated>{data($x/user_updated)}</hmis:user_updated>
</hmis:Client>
}
</hmis:Export>
</hmis:Source></hmis:Sources>');
Output
<hmis:Sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:hmis="https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd">
<hmis:Source>
<hmis:SourceID>10</hmis:SourceID>
<hmis:Export>
<ExportID>111</ExportID>
<ExportDate>0</ExportDate>
<ExportPeriod>
<StartDate>0</StartDate>
<EndDate>0</EndDate>
</ExportPeriod>
<hmis:Client DateCreated="2022-03-02" DateUpdated="2022-03-02">
<hmis:PersonalID>111</hmis:PersonalID>
<hmis:first_name>Alpha</hmis:first_name>
<hmis:last_name>Brown</hmis:last_name>
<hmis:birth_date>2000-01-01</hmis:birth_date>
<hmis:CustomClientElements>
<hmis:CaseManager_PH>Manager Alpha</hmis:CaseManager_PH>
<hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo>
</hmis:CustomClientElements>
<hmis:user_updated>AW3</hmis:user_updated>
</hmis:Client>
<hmis:Client DateCreated="2022-03-03" DateUpdated="2022-03-03">
<hmis:PersonalID>222</hmis:PersonalID>
<hmis:first_name>Bobby</hmis:first_name>
<hmis:last_name>Dow</hmis:last_name>
<hmis:birth_date>2000-01-01</hmis:birth_date>
<hmis:CustomClientElements>
<hmis:CaseManager_PH>Manager2222</hmis:CaseManager_PH>
<hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo>
</hmis:CustomClientElements>
<hmis:user_updated>BBX3</hmis:user_updated>
</hmis:Client>
</hmis:Export>
</hmis:Source>
</hmis:Sources>

You mentioned Explicit, so here is solution generated with FOAM. Not that pretty for some but works OK though could have some limitation with super fancy formats and some casese with maxOccurs="0". It also might require some manual tweaking.
I made single table c just as my personal preference, which required me to add top 1 into few levels manually. But also works fine with join
/* --------------------TEST DATA
drop table if exists #tbl
Create table #tbl (
PersonalID INT , first_name VARCHAR(30), last_name VARCHAR(30), birth_date DATE, CaseManager_PH VARCHAR(30), Female BIT, ExportDate DATE, user_updated VARCHAR(30) );
INSERT INTO #tbl
VALUES
(111, 'Alpha', 'Brown', '2000-01-01', 'Manager Alpha', 0, '2022-03-02', 'AW3'),
(222, 'Bobby', 'Dow', '2002-02-02', 'Manager2222', 0 , '2022-03-03', 'BBX3');
create table #export (ExportDate date , StartDate DATE, EndDate date);
INSERT INTO #export (ExportDate, StartDate, EndDate) VALUES
('2022-03-22', '2022-01-01', '2022-04-04');
-- select * from #export
-- select * from #tbl
-- drop table c
Select * into c from (
select c.*, e.StartDate, e.EndDate
, hmis =cast('https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd' as varchar(255))
, ExportID = '111', SourceID = '10', ContactInfo = 'Unknown'
from #tbl c
join #export e on 1=1
) c
Select * from c
*/
/********************************************
* Output produced by Foam #
* 3/31/2022 12:12:03 PM
*
* digital nothing design
* http://www.digitalnothing.com
********************************************/
SELECT Tag = 1, Parent = NULL,
[hmis:Sources!1!xmlns:hmis] = 'https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd',
[hmis:Source!2!] = NULL,
[hmis:Source!2!hmis:SourceID!element] = NULL,
[hmis:Export!3!] = NULL,
[hmis:Export!3!ExportID!element] = NULL,
[hmis:Export!3!ExportDate!element] = NULL,
[ExportPeriod!4!] = NULL,
[ExportPeriod!4!StartDate!element] = NULL,
[ExportPeriod!4!EndDate!element] = NULL,
[hmis:Client!5!DateCreated] = NULL,
[hmis:Client!5!DateUpdated] = NULL,
[hmis:Client!5!hmis:PersonalID!element] = NULL,
[hmis:Client!5!hmis:first_name!element] = NULL,
[hmis:Client!5!hmis:last_name!element] = NULL,
[hmis:Client!5!hmis:birth_date!element] = NULL,
[hmis:CustomClientElements!6!] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL,
[hmis:Client!5!hmis:user_updated!element] = NULL
UNION ALL
SELECT top 1 Tag = 2, Parent = 1,
[hmis:Sources!1!xmlns:hmis] = NULL,
[hmis:Source!2!] = NULL,
[hmis:Source!2!hmis:SourceID!element] = c.SourceID,
[hmis:Export!3!] = NULL,
[hmis:Export!3!ExportID!element] = NULL,
[hmis:Export!3!ExportDate!element] = NULL,
[ExportPeriod!4!] = NULL,
[ExportPeriod!4!StartDate!element] = NULL,
[ExportPeriod!4!EndDate!element] = NULL,
[hmis:Client!5!DateCreated] = NULL,
[hmis:Client!5!DateUpdated] = NULL,
[hmis:Client!5!hmis:PersonalID!element] = NULL,
[hmis:Client!5!hmis:first_name!element] = NULL,
[hmis:Client!5!hmis:last_name!element] = NULL,
[hmis:Client!5!hmis:birth_date!element] = NULL,
[hmis:CustomClientElements!6!] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL,
[hmis:Client!5!hmis:user_updated!element] = NULL
from c
UNION ALL
SELECT top 1 Tag = 3, Parent = 2,
[hmis:Sources!1!xmlns:hmis] = NULL,
[hmis:Source!2!] = NULL,
[hmis:Source!2!hmis:SourceID!element] = NULL,
[hmis:Export!3!] = NULL,
[hmis:Export!3!ExportID!element] = c.ExportID,
[hmis:Export!3!ExportDate!element] = c.ExportDate,
[ExportPeriod!4!] = NULL,
[ExportPeriod!4!StartDate!element] = NULL,
[ExportPeriod!4!EndDate!element] = NULL,
[hmis:Client!5!DateCreated] = NULL,
[hmis:Client!5!DateUpdated] = NULL,
[hmis:Client!5!hmis:PersonalID!element] = NULL,
[hmis:Client!5!hmis:first_name!element] = NULL,
[hmis:Client!5!hmis:last_name!element] = NULL,
[hmis:Client!5!hmis:birth_date!element] = NULL,
[hmis:CustomClientElements!6!] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL,
[hmis:Client!5!hmis:user_updated!element] = NULL
from c
UNION ALL
SELECT top 1 Tag = 4, Parent = 3,
[hmis:Sources!1!xmlns:hmis] = NULL,
[hmis:Source!2!] = NULL,
[hmis:Source!2!hmis:SourceID!element] = NULL,
[hmis:Export!3!] = NULL,
[hmis:Export!3!ExportID!element] = NULL,
[hmis:Export!3!ExportDate!element] = NULL,
[ExportPeriod!4!] = NULL,
[ExportPeriod!4!StartDate!element] = c.StartDate,
[ExportPeriod!4!EndDate!element] = c.EndDate,
[hmis:Client!5!DateCreated] = NULL,
[hmis:Client!5!DateUpdated] = NULL,
[hmis:Client!5!hmis:PersonalID!element] = NULL,
[hmis:Client!5!hmis:first_name!element] = NULL,
[hmis:Client!5!hmis:last_name!element] = NULL,
[hmis:Client!5!hmis:birth_date!element] = NULL,
[hmis:CustomClientElements!6!] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL,
[hmis:Client!5!hmis:user_updated!element] = NULL
from c
UNION ALL
SELECT Tag = 5, Parent = 3,
[hmis:Sources!1!xmlns:hmis] = NULL,
[hmis:Source!2!] = NULL,
[hmis:Source!2!hmis:SourceID!element] = NULL,
[hmis:Export!3!] = NULL,
[hmis:Export!3!ExportID!element] = NULL,
[hmis:Export!3!ExportDate!element] = NULL,
[ExportPeriod!4!] = NULL,
[ExportPeriod!4!StartDate!element] = NULL,
[ExportPeriod!4!EndDate!element] = NULL,
[hmis:Client!5!DateCreated] = c.ExportDate,
[hmis:Client!5!DateUpdated] = c.ExportDate,
[hmis:Client!5!hmis:PersonalID!element] = c.PersonalID,
[hmis:Client!5!hmis:first_name!element] = c.first_name,
[hmis:Client!5!hmis:last_name!element] = c.last_name,
[hmis:Client!5!hmis:birth_date!element] = c.birth_date,
[hmis:CustomClientElements!6!] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL,
[hmis:Client!5!hmis:user_updated!element] = c.user_updated
from c
UNION ALL
SELECT Tag = 6, Parent = 5,
[hmis:Sources!1!xmlns:hmis] = NULL,
[hmis:Source!2!] = NULL,
[hmis:Source!2!hmis:SourceID!element] = NULL,
[hmis:Export!3!] = NULL,
[hmis:Export!3!ExportID!element] = NULL,
[hmis:Export!3!ExportDate!element] = NULL,
[ExportPeriod!4!] = NULL,
[ExportPeriod!4!StartDate!element] = NULL,
[ExportPeriod!4!EndDate!element] = NULL,
[hmis:Client!5!DateCreated] = NULL,
[hmis:Client!5!DateUpdated] = NULL,
[hmis:Client!5!hmis:PersonalID!element] = c.PersonalID,
[hmis:Client!5!hmis:first_name!element] = NULL,
[hmis:Client!5!hmis:last_name!element] = NULL,
[hmis:Client!5!hmis:birth_date!element] = NULL,
[hmis:CustomClientElements!6!] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = ISNULL(c.Casemanager_PH,''),
[hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = ISNULL(c.ContactInfo,''),
[hmis:Client!5!hmis:user_updated!element] = NULL
from c
ORDER BY
[hmis:Client!5!hmis:PersonalID!element] ASC,
Tag
FOR XML EXPLICIT
-- sample xml with column names as element values used in FOAM
/*
<hmis:Sources xmlns:hmis="https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd" >
<hmis:Source>
<hmis:SourceID>c.SourceID</hmis:SourceID>
<hmis:Export>
<ExportID>c.ExportID</ExportID>
<ExportDate>c.ExportDate</ExportDate>
<ExportPeriod>
<StartDate>c.StartDate</StartDate>
<EndDate>c.EndDate</EndDate>
</ExportPeriod>
<hmis:Client DateCreated = "c.ExportDate" DateUpdated="c.ExportDate" >
<hmis:PersonalID>c.PersonalID</hmis:PersonalID>
<hmis:first_name>c.first_name</hmis:first_name>
<hmis:last_name>c.last_name</hmis:last_name>
<hmis:birth_date>c.birth_date</hmis:birth_date>
<hmis:CustomClientElements>
<hmis:Casemanager_PH>c.Casemanager_PH</hmis:Casemanager_PH>
<hmis:Casemanager_ContactInfo>c.ContactInfo</hmis:Casemanager_ContactInfo>
</hmis:CustomClientElements>
<hmis:user_updated>c.user_updated</hmis:user_updated>
</hmis:Client>
</hmis:Export>
</hmis:Source>
</hmis:Sources>
*/

Related

How can we create users with the same email but not the same workflow?

I want to make it possible to create several users, even with the same email address as long as they do not have the same "IdWorkflow" number.
But obviously it doesn't work... result.Succeeded is always false. & all I have is that message : "User name 'test#test.com' is already taken."
What can I do...?
Register.cshtml.cs
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, IdWorkflow = Input.IdWorkflow };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
AspNetUsers.sql
CREATE TABLE [dbo].[AspNetUsers] (
[Id] NVARCHAR (450) NOT NULL,
[UserName] NVARCHAR (256) NULL,
[NormalizedUserName] NVARCHAR (256) NULL,
[Email] NVARCHAR (256) NULL,
[NormalizedEmail] NVARCHAR (256) NULL,
[EmailConfirmed] BIT NOT NULL,
[PasswordHash] NVARCHAR (MAX) NULL,
[SecurityStamp] NVARCHAR (MAX) NULL,
[ConcurrencyStamp] NVARCHAR (MAX) NULL,
[PhoneNumber] NVARCHAR (MAX) NULL,
[PhoneNumberConfirmed] BIT NOT NULL,
[TwoFactorEnabled] BIT NOT NULL,
[LockoutEnd] DATETIMEOFFSET (7) NULL,
[LockoutEnabled] BIT NOT NULL,
[AccessFailedCount] INT NOT NULL,
[DateCreate] DATETIME2 (7) DEFAULT ('0001-01-01T00:00:00.0000000') NOT NULL,
[DateUpdate] DATETIME2 (7) DEFAULT ('0001-01-01T00:00:00.0000000') NOT NULL,
[IdWorkflow] NVARCHAR (450) NULL,
CONSTRAINT [PK_AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex]
ON [dbo].[AspNetUsers]([NormalizedUserName] ASC, [IdWorkflow] ASC) WHERE ([NormalizedUserName] IS NOT NULL);

Remove transformation is not working for a column

I am trying out a scenario where tables of two databases in MySQL are synchronized and in some places, columns are transformed. I have a perticular case where every column of DB1 table while insertion, will be synchronized (a new row will be inserted in DB2) but for updating that row, a specific column will have no effect on DB2 table (every other column will be updated). I am trying to achieve this by 'remove transformation' (one of the transformation types). But my remove transformation is not working. Other transformations are working fine. May be I have missed a thing. A little help will be much appreciated.
DB1: records_new Table: employee
CREATE TABLE `employee` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`title` varchar(11) DEFAULT 'Mr.',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
DB2: records_new_replica Table: employee
CREATE TABLE `employee` (
`id` bigint(20) NOT NULL,
`emp_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`title` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`designation` varchar(100) DEFAULT NULL,
`name` varchar(100) DEFAULT NULL,
`time` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
////////////////////////////////////////////////////////sym tables//////////////////////////////////////////////////////////
sym_node_group
INSERT INTO records.sym_node_group
(node_group_id, description, create_time, last_update_by, last_update_time)
VALUES('records', NULL, NULL, NULL, NULL);
INSERT INTO records.sym_node_group
(node_group_id, description, create_time, last_update_by, last_update_time)
VALUES('records-replica', NULL, NULL, NULL, NULL);
sym_node
INSERT INTO records.sym_node
(node_id, node_group_id, external_id, sync_enabled, sync_url, schema_version, symmetric_version, config_version, database_type, database_version, batch_to_send_count, batch_in_error_count, created_at_node_id, deployment_type, deployment_sub_type)
VALUES('000', 'records', '000', 1, 'http://localhost:31415/sync/records-000', '?', '3.10.4', '3.10.4', 'MySQL', '8.0', -1, -1, NULL, 'server', NULL);
INSERT INTO records.sym_node
(node_id, node_group_id, external_id, sync_enabled, sync_url, schema_version, symmetric_version, config_version, database_type, database_version, batch_to_send_count, batch_in_error_count, created_at_node_id, deployment_type, deployment_sub_type)
VALUES('2000', 'records-replica', '2000', 1, 'http://DESKTOP-KSP9CJD:31415/sync/records-replica-1000', '?', '3.10.4', '3.10.4', 'MySQL', '8.0', -1, -1, '000', 'server', NULL);
sym_router
INSERT INTO records.sym_router
(router_id, target_catalog_name, target_schema_name, target_table_name, source_node_group_id, target_node_group_id, router_type, router_expression, sync_on_update, sync_on_insert, sync_on_delete, use_source_catalog_schema, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-new', '', '', '', 'records', 'records-replica', 'default', '', 1, 1, 0, 1, '2019-10-30 09:40:25', NULL, '2019-10-30 09:40:25', '');
sym_trigger
INSERT INTO records.sym_trigger
(trigger_id, source_catalog_name, source_schema_name, source_table_name, channel_id, reload_channel_id, sync_on_update, sync_on_insert, sync_on_delete, sync_on_incoming_batch, name_for_update_trigger, name_for_insert_trigger, name_for_delete_trigger, sync_on_update_condition, sync_on_insert_condition, sync_on_delete_condition, custom_before_update_text, custom_before_insert_text, custom_before_delete_text, custom_on_update_text, custom_on_insert_text, custom_on_delete_text, external_select, tx_id_expression, channel_expression, excluded_column_names, included_column_names, sync_key_names, use_stream_lobs, use_capture_lobs, use_capture_old_data, use_handle_key_updates, stream_row, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-trig_new', 'records_new', '', 'employee', 'employee', 'reload', 1, 1, 0, 0, NULL, NULL, NULL, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', 0, 0, 1, 1, 0, '2019-10-30 09:38:56', NULL, '2019-10-30 09:38:56', '');
sym_trigger_router
INSERT INTO records.sym_trigger_router
(trigger_id, router_id, enabled, initial_load_order, initial_load_select, initial_load_delete_stmt, ping_back_enabled, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-trig_new', 'emp-2-emp-new', 1, 1, '', '', 0, '2019-10-30 09:41:31', NULL, '2019-10-30 09:41:31', '');
sym_transform_table
INSERT INTO records.sym_transform_table
(transform_id, source_node_group_id, target_node_group_id, transform_point, source_catalog_name, source_schema_name, source_table_name, target_catalog_name, target_schema_name, target_table_name, update_first, update_action, delete_action, transform_order, column_policy, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-new', 'records', 'records-replica', 'LOAD', 'records_new', NULL, 'employee', 'records_new_replica', NULL, 'employee', 0, 'UPDATE_COL', 'NONE', 1, 'IMPLIED', '2019-10-30 11:38:22', NULL, '2019-10-30 11:38:22', '');
sym_transform_column
INSERT INTO records.sym_transform_column
(transform_id, include_on, target_column_name, source_column_name, pk, transform_type, transform_expression, transform_order, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-new', '*', 'emp_name', 'name', 0, 'copy', '', 1, '2019-10-30 11:38:49', NULL, '2019-10-30 11:38:49', '');
INSERT INTO records.sym_transform_column
(transform_id, include_on, target_column_name, source_column_name, pk, transform_type, transform_expression, transform_order, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-new', '*', 'time', NULL, 0, 'lookup', 'select UNIX_TIMESTAMP()', 1, '2019-10-31 10:01:02', NULL, '2019-10-31 10:01:02', '');
INSERT INTO records.sym_transform_column
(transform_id, include_on, target_column_name, source_column_name, pk, transform_type, transform_expression, transform_order, create_time, last_update_by, last_update_time, description)
VALUES('emp-2-emp-new', 'U', 'title', 'title', 0, 'remove', '', 1, '2019-11-06 13:20:21', '', '2019-11-06 13:20:21', '');
Thanks in advance.:)
I wanted to delete this question. But i figured that may be...if someone stumbled upon symmetricds and after reading the user guide..missed a corner and that became a doom for him...only for those...here it goes:
In the guide, when describing fields of sym_router table, it is stated about the Use Source Catalog/Schema field that
If set then the source catalog and source schema are sent to the target to be used to find the target table.
and in appendix/ROUTER it is stated about USE_SOURCE_CATALOG_SCHEMA that,
Whether or not to assume that the target catalog/schema name should be the same as the source catalog/schema name. The target catalog or schema name will still override if not blank.
Now lets see what might override those target variables. In Transform section, they have stated the following:
Source Catalog
Name of the catalog of the configured source table. This should only be set if Use Source Catalog/Schema or Target Catalog are set on the Router.
Source Schema
Name of the schema for the configured source table. This should only be set if Use Source Catalog/Schema or Target Schema are set on the Router.
So, the resolution is, when I have set the source_catalog_name in sym_transform_table, then I have to set the use_source_catalog_schema in sym_router table and as my tables which I intended to sync is not in the default catalog then I have to explicitly set the other two columns e.g. target_catalog_name and target_table_name in sym_transform_table.
tl;dr, set the use_source_catalog_schema in table sym_router to 1 if source_catalog_name is set in the sym_transform_table for transformation and another thing...read the guide.it's brief but it's our only friend.

Requires that my function is implemented access to the database

Requires that my function is implemented access to the databaseand certain operations were carried out.
Such as:
1) Check or read the message.
2) Checking and issuing all communications between users by date.
3) Find the latest posts from all users.
But I though there is material in the tutorial I could not figure out how to do. All I could show you. Therefore, I want to ask you to see my code and see what's up there and help me out. You do not need to completely write code. Just if it's not hard for you to sink your sleeves and calmly give examples let me write these three functions on LINQ and EntityFramework
MY CODE:
public bool CheckIfUnreadMessagesArePresent(int userId)
{
IList<MessageInfo> messageInfo = new List<MessageInfo>();
MessageInfo messageIn = new MessageInfo();
var sql = #"SELECT * FROM MessageInfo
WHERE wasRead = 0 AND Id = #userId ORDER BY date DESC";
var meassage = dataBaseContext.Database.SqlQuery<MessageInfo>(sql, new { userId = messageIn.Id });
return messageInfo.Any(messageIn.WasRead == true);
}
public IList<UserInfo> FetchMessagesFromConversation(int userID1, int userID2)
{
IList<UserInfo> messageInfo = new List<UserInfo>();
MessageInfo messageIn = new MessageInfo();
var sql = #"SELECT * FROM MessageInfo
WHERE userID1 = 1 AND userID2 = 3 OR userID1 = 3 AND userID2 = 1 order by date DESC";
var meassage = dataBaseContext.Database.SqlQuery<MessageInfo>(sql, new { userID1 = messageIn.SenderId,userID2 = messageIn.ReceiverId});
messageInfo.Insert(message);
return messageInfo;
}
public IList<MessageInfo> FetchLastMessageFromEachConversation((int userID))
{
IList<UserInfo> messageInfo = new List<UserInfo>();
MessageInfo messageIn = new MessageInfo();
var sql = #"SELECT * FROM MessageInfo
WHERE date IN (#SELECT max(date)
FROM MessageInfo WHRERE date IN (
SELECT max(date)
FROM MessageInfo
GROUP BY messageIn.ID, messageIn.ReceiverId
ORDER BY date DESC, messageIn.ID, messageIn.ReceiverId)
GROUP BY if (messageIn.ID < messageIn.ReceiverId,
concat(messageIn.ID, " - ", messageIn.ReceiverId), concat(messageIn.ReceiverId, " - ", messageIn.ID)))";
var meassage = dataBaseContext.Database.SqlQuery<MessageInfo>(sql, new { userID1 = messageIn.SenderId, userID2 = messageIn.ReceiverId });
return messageInfo;
}
My DataBase
CREATE TABLE [dbo].[UserInfo](
[Id] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Login] [varchar](50) NOT NULL,
[Password] [varchar](50) NOT NULL,
[FirstName] [nchar](10) NOT NULL,
[LastName] [nchar](10) NOT NULL,
[Email] [varchar](50) NOT NULL,
[RegistrationDate] [datetime] NOT NULL,
)
GO
CREATE TABLE [dbo].[Messages](
[Id] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[SenderId] [int] NOT NULL,
[ReceiverId] [int] NOT NULL,
[Message] [varchar](500) NOT NULL,
[date] [datetime] NOT NULL,
[WasRead][bit] NOT NULL
CONSTRAINT FK_UserInfoSender FOREIGN KEY (SenderId)
REFERENCES [UserInfo](Id),
CONSTRAINT FK_UserInfoReceiver FOREIGN KEY (ReceiverId)
REFERENCES [UserInfo](Id)
)
GO

Incorrect output from stored procedure

I am using below stored procedure to generate a crystal report.My report mainly filters data based on two possible values, Arcade or Franchise.
I filter data as Arcade = 1 , Franchise = 2 and Both = 0.The OutletType parameter get these int values.
When I filter for one particular value It gives me both arcade and franchise values.
ALTER PROCEDURE [dbo].[PrintReceiptCancellationWorkflow]
#EntryType int,
#OutletType int,
#RequestedUser varchar(50),
#FromDate DateTime2,
#ToDate DateTime2,
#OutletCode varchar(10),
#CancelledUser varchar(20),
#Status int
AS
BEGIN
SELECT
Outlets.OutletDesc AS 'Branch',
Receipt.CancelUser AS 'RequestedBy',
Receipt.RecDate AS 'ReqDateTime',
--ReceiptCancellationStatus.ApprovedStatus AS 'Status',
ReceiptCancellationStatus.StatusDesc As Status,
WorkflowRequestQueue.CposReference AS 'WCRNo',
Receipt.ReceiptNo AS 'ReceiptNo',
Receipt.PaymentMode AS 'PaymentMode',
Receipt.AppliedAmount AS 'Amount',
WorkflowRequestQueue.AppRejUser AS 'CompletedBy',
WorkflowRequestQueue.AppRejDateTime AS 'CompletedDateTime',
EntryTypes.EntryType AS 'PaymentCategory',
WorkflowRequestQueue.AppRejComment AS 'Comment',
OutletCategories.CatDesc As 'OutletType'
FROM Receipt
INNER JOIN
Outlets ON Receipt.OutletCode = Outlets.OutletCode
LEFT OUTER JOIN
EntryTypes ON Receipt.EntryTypeId = EntryTypes.Id
LEFT OUTER JOIN
WorkflowRequestQueue ON Receipt.CposReference = WorkflowRequestQueue.CposReference
LEFT OUTER JOIN
OutletCategories ON Outlets.OutletType = OutletCategories.CatCode
LEFT OUTER JOIN
ReceiptCancellationStatus ON WorkflowRequestQueue.ApprovedStatus = ReceiptCancellationStatus.Id
WHERE (Outlets.OutletType = #OutletType OR Outlets.OutletType = 0) OR
(Receipt.EntryTypeId = #EntryType OR Receipt.EntryTypeId = 0) OR
Receipt.CancelUser = #RequestedUser OR
(( CONVERT(DATE,WorkflowRequestQueue.AppRejDateTime) >= #FromDate) AND ( CONVERT(DATE,WorkflowRequestQueue.AppRejDateTime) <= #ToDate)) OR
Outlets.OutletCode = #OutletCode OR
WorkflowRequestQueue.ApprovedPerson = #CancelledUser OR
(WorkflowRequestQueue.ApprovedStatus = #Status OR WorkflowRequestQueue.ApprovedStatus = 0)
END
Outlet type drop down values,
$scope.VendorDropdown = [
{ "text": "Select", "value": "0" },
{ "text": "Arcade", "value": "1" },
{ "text": "Franchise", "value": "2" },
];
Report generation code,
object paymentCategory = Convert.ToInt32(Request.Form["PaymentCategory"]);
object vendor = Convert.ToInt32(Request.Form["Vendor"]);
object requestedUser = Convert.ToString(Request.Form["RequestedUser"]);
object cancelledUser = Convert.ToString(Request.Form["CancelledUser"]);
object Fromdate = Convert.ToDateTime(Request.Form["dateFrom"]);
object Todate = Convert.ToDateTime(Request.Form["dateTo"]);
object status = Convert.ToInt32(Request.Form["Status"]);
object outlet = Convert.ToString(Request.Form["Outlet"]);
if (isExcel)
{
myReport.Load(Server.MapPath("~/CPOSReport/MIS/CancellationReports/ReceiptCancellationWorkFlow.rpt"));
}
else {
myReport.Load(Server.MapPath("~/CPOSReport/MIS/CancellationReports/ReceiptCancellationWorkFlow.rpt"));
}
myReport.SetParameterValue("#EntryType", paymentCategory);
myReport.SetParameterValue("#OutletType",vendor );
myReport.SetParameterValue("#RequestedUser", requestedUser);
myReport.SetParameterValue("#CancelledUser", cancelledUser);
myReport.SetParameterValue("#FromDate", Fromdate);
myReport.SetParameterValue("#ToDate", Todate);
myReport.SetParameterValue("#Status", status);
myReport.SetParameterValue("#OutletCode", outlet);
All of your where conditions are OR'ed. This means that if one of them are satisfied, the row will be included.
You should probably try this WHERE in stead with the different conditions AND'ed together:
WHERE (Outlets.OutletType = #OutletType OR Outlets.OutletType = 0) AND
(Receipt.EntryTypeId = #EntryType OR Receipt.EntryTypeId = 0) AND
Receipt.CancelUser = #RequestedUser AND
(
( CONVERT(DATE,WorkflowRequestQueue.AppRejDateTime) >= #FromDate) AND
( CONVERT(DATE,WorkflowRequestQueue.AppRejDateTime) <= #ToDate)
) AND
Outlets.OutletCode = #OutletCode AND
WorkflowRequestQueue.ApprovedPerson = #CancelledUser AND
(WorkflowRequestQueue.ApprovedStatus = #Status OR WorkflowRequestQueue.ApprovedStatus = 0)

phonegap database error code 5 - non an error

I am using phonegap to access the phone database. But my create process calls everytime the error routine with error code: 5 and message: non an error?
Isn't it possible to execute multiple sql statements in one transaction?
SQLite Expert couldnt find an syntax error...
createDB: function(error, success) {
if(typeof error != 'function') error = this.errorDB;
if(typeof success != 'function') success = this.successDB;
sql = "DROP TABLE IF EXISTS `boiler`; "
+"CREATE TABLE IF NOT EXISTS `boiler` ( "
+" `id` int NOT NULL, `object` int NOT NULL, `number` varchar(100) NOT NULL, "
+" `volume` double DEFAULT NULL, `brand` varchar(100) DEFAULT NULL, `year` year(4) DEFAULT NULL, "
+" `price_before` float NOT NULL DEFAULT '0', `price_after` float NOT NULL DEFAULT '0', `description` TEXT DEFAULT NULL, "
+" `img1` varchar(200) DEFAULT NULL, `img2` varchar(200) DEFAULT NULL, `img3` varchar(200) DEFAULT NULL, "
+" `img4` varchar(200) DEFAULT NULL, `img5` varchar(200) DEFAULT NULL, `img6` varchar(200) DEFAULT NULL, "
+" `img7` varchar(200) DEFAULT NULL, `img8` varchar(200) DEFAULT NULL, `img9` varchar(200) DEFAULT NULL, "
+"PRIMARY KEY (`id`)); "
+"DROP TABLE IF EXISTS `counter`; "
+"CREATE TABLE IF NOT EXISTS `counter` ( "
+" `number` varchar(100) NOT NULL, `object` int NOT NULL, `type` tinyint NOT NULL DEFAULT '0', "
+" `value` double DEFAULT NULL, `access` varchar(100) DEFAULT NULL, "
+"PRIMARY KEY (`number`)); "
+"DROP TABLE IF EXISTS `link`; "
+"CREATE TABLE IF NOT EXISTS `link` ( "
+" `id` int NOT NULL, `boiler` int NOT NULL, `name` varchar(100) DEFAULT NULL, "
+" `units` tinyint DEFAULT NULL, `price` float NOT NULL DEFAULT '0', "
+"PRIMARY KEY (`id`)); "
+"DROP TABLE IF EXISTS `manager`; "
+"CREATE TABLE IF NOT EXISTS `manager` ( "
+" `id` int NOT NULL, `company` varchar(100) DEFAULT NULL, `name` varchar(100) NOT NULL, "
+" `phone` varchar(15) DEFAULT NULL, "
+"PRIMARY KEY (`id`)); "
+"DROP TABLE IF EXISTS `object`; "
+"CREATE TABLE IF NOT EXISTS `object` ( "
+" `id` int NOT NULL, `state` tinyint NOT NULL DEFAULT '0', `user` varchar(50) DEFAULT NULL, "
+" `date` char(15) DEFAULT NULL, `street` varchar(100) DEFAULT NULL, `number` varchar(16) DEFAULT NULL, "
+" `zip` char(5) DEFAULT NULL, `city` varchar(100) DEFAULT NULL, `manager` int NOT NULL DEFAULT '0', "
+" `units` int NOT NULL DEFAULT '0', "
+"PRIMARY KEY (`id`));";
console.log(sql);
this.DB.transaction(function (tx) { tx.executeSql(sql); }, error, success);
},
don't know the error code: 5 but you can execute the multiple sql statements
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
// Populate the database
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
//here you can do multiple sql statements.
}
// Transaction error callback
function errorCB(err) {
alert("Error processing SQL: "+err);
}
// Transaction success callback
function successCB() {
alert("success!");
}
link here
Please Check Your Database From File Explorer
there is problem only in the creation of table like you are entering four values but in your table there are only three columns so this error occours
tx.executeSql("CREATE TABLE IF NOT EXISTS quotes(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,name,flag INTEGER,address,description,phone_number,date INTEGER,quote_number,job,images)");
Error is due to if you are assigning directly integer value instead of var type value
like for flar i am using 1 or 0
but now i store this value in var type

Resources