Update row null fields with values from similar rows (same "key") - mysql

My question is kind of hard to explain in title so I'll show the data and goal.
There is a MySQL table with following structure:
CREATE TABLE customerProjectData(
idCustomer INT NOT NULL,
idProject INT DEFAULT NULL,
comePersons SMALLINT DEFAULT NULL,
comePairs SMALLINT DEFAULT NULL,
comment VARCHAR(255) DEFAULT NULL,
idCity INT DEFAULT NULL,
idStreet INT DEFAULT NULL,
name VARCHAR(64) DEFAULT NULL,
surname VARCHAR(64) DEFAULT NULL,
homeNum VARCHAR(10) DEFAULT NULL,
postCode CHAR(6) DEFAULT NULL,
postCity VARCHAR(64) DEFAULT NULL,
cellPhone VARCHAR(12) DEFAULT NULL
)
The thing is, there shold be also PRIMARY KEY(idCustomer, idProject) defined and it's not. As a result There are kind of duplicates (with the same primary key) but with different data.
I could run ALTER IGNORE TABLE but data loss would probably be unacceptable and unpredicatable. Finally we decided to try to fill null fields with values from duplicates if they contain data and after that run the ALTER IGNORE TABLE. Much less data will be lost that way and it's acceptable in this case (it's better than leaving it as it is now in longer time perspective).
The question is how to fill those fields from each duplicate.

Here is a rough try.
First try to find out the no. of rows which have the same key.
<?php
// $link is the database identifier
$sql = 'SELECT COUNT(*) AS num, * FROM `customerProjectData` GROUP BY `idCustomer`, `idProject` HAVING COUNT(*) > 1 ORDER BY COUNT(*) ASC;';
$run = mysql_query( $sql, $link );
$rows = array();
if( $run && mysql_num_rows( $run ) ) {
while( ( $fetch = mysql_fetch_assoc( $run ) ) !== false ) {
$rows[] = $fetch;
}
}
?>
Now $rows contains a list of all rows which have the same key and a count of how many times this key has been repeated in the table.
You can write a function which then iterates count times and see which rows has the complete data and use that to populates other records with this record's data.
A bit of trial and error.

I used #web-nomad suggestion and did something similar, but in sql procedure:
DROP PROCEDURE IF EXISTS correctCPD$$
CREATE PROCEDURE correctCPD()
BEGIN
DECLARE currentCustomerId INT;
DECLARE currentProjectId INT;
DECLARE cur_idCustomer INT;
DECLARE cur_idProject INT;
DECLARE cur_comePersons SMALLINT;
DECLARE cur_comePairs SMALLINT;
DECLARE cur_comment VARCHAR(255);
DECLARE cur_idCity INT;
DECLARE cur_idStreet INT;
DECLARE cur_name VARCHAR(64);
DECLARE cur_surname VARCHAR(64);
DECLARE cur_homeNum VARCHAR(10);
DECLARE cur_postCode CHAR(6);
DECLARE cur_postCity VARCHAR(64);
DECLARE cur_cellPhone VARCHAR(12);
CREATE TEMPORARY TABLE ids (
idCustomer INT,
idProject INT
) ENGINE = InnoDB;
INSERT INTO ids
SELECT idCustomer, idProject FROM customerprojectdata group by idCustomer, idProject having count(*) > 1;
BLOCK1: BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE itemCur CURSOR FOR SELECT idCustomer, idProject FROM ids;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN itemCur;
itemCurLoop: LOOP
FETCH itemCur INTO currentCustomerId, currentProjectId;
IF done THEN
LEAVE itemCurLoop;
END IF;
BLOCK2: BEGIN
DECLARE doneIn INT DEFAULT FALSE;
DECLARE cpdCur CURSOR FOR SELECT idCustomer, idProject, comePersons, comePairs, comment, idCity, idStreet, name, surname, homeNum, postCode, postCity, cellPhone FROM customerProjectData WHERE idCustomer = currentCustomerId AND idProject = currentProjectId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET doneIn = TRUE;
OPEN cpdCur;
cpdCurLoop: LOOP
FETCH cpdCur INTO
cur_idCustomer, cur_idProject, cur_comePersons, cur_comePairs,
cur_comment, cur_idCity, cur_idStreet, cur_name, cur_surname,
cur_homeNum, cur_postCode, cur_postCity, cur_cellPhone;
IF doneIn THEN
LEAVE cpdCurLoop;
END IF;
UPDATE CustomerProjectData SET
comePersons = IF((comePersons IS NULL OR comePersons = '') AND cur_comePersons > 0, cur_comePersons, comePersons),
comePairs = IF((comePairs IS NULL OR comePairs = '') AND cur_comePairs > 0, cur_comePairs, comePairs),
comment = IF((comment IS NULL OR comment = '') AND cur_comment > 0, cur_comment, comment),
idCity = IF((idCity IS NULL AND idStreet IS NULL) AND cur_idCity > 0, cur_idCity, idCity),
idStreet = IF(((idCity IS NULL OR idCity = cur_idCity) AND idStreet IS NULL) AND cur_idStreet > 0, cur_idStreet, idStreet),
name = IF((name IS NULL OR name = '') AND cur_name > 0, cur_name, name),
surname = IF((surname IS NULL OR surname = '') AND cur_surname > 0, cur_surname, surname),
homeNum = IF((homeNum IS NULL OR homeNum = '') AND cur_homeNum > 0, cur_homeNum, homeNum),
postCode = IF((postCode IS NULL OR postCode = '') AND cur_postCode > 0, cur_postCode, postCode),
postCity = IF((postCity IS NULL OR postCity = '') AND cur_postCity > 0, cur_postCity, postCity),
cellPhone = IF((cellPhone IS NULL OR cellPhone = '') AND cur_cellPhone > 0, cur_cellPhone, cellPhone)
WHERE idCustomer = currentCustomerId AND idProject = currentProjectId;
END LOOP;
CLOSE cpdCur;
END BLOCK2;
END LOOP;
CLOSE itemCur;
END BLOCK1;
DROP TEMPORARY TABLE ids;
END$$
Thanks for help!

Related

How to write an update statement to update columns and check for prime numbers?

I am just learning to code SQL. Can someone help me with an update statement, I have done the insert but am stuck with an update. My table prime_test has two columns number and is_prime
Here is the question:
Write one or more update statements that sets the 'is_prime' column for each associated integer. For a prime, the column should read 'prime'. For non-primes, the column should read 'composite'.
My code
CREATE TABLE `sql_inventory`.`prime_test` (
`number` INT NOT NULL,
`is_prime` VARCHAR(50) NULL,
PRIMARY KEY (`number`));
INSERT INTO `prime`.`prime_test`
(`number`)
VALUES
(rand()*(100-2+1)+2);
Function to find the prime numbers:
CREATE FUNCTION isPrime(#num int)
RETURNS VARCHAR(50)
BEGIN
DECLARE #prime_or_notPrime INT
DECLARE #counter INT
DECLARE #retVal VARCHAR(50)
SET #retVal = 'composite'
SET #prime_or_notPrime = 1
SET #counter = 2
WHILE (#counter <= #number/2 )
BEGIN
IF (( #number % #counter) = 0 )
BEGIN
set #prime_or_notPrime = 0
BREAK
END
IF (#prime_or_notPrime = 1 )
BEGIN
SET #retVal = 'prime'
END
SET #counter = #counter + 1
END
return #retVal
END
update prime_test
set is_prime = dbo.isPrime(select number From 'prime'.'prime_test')

Optional OrderBy parameter in MySql Stored Procedure

I'm being passed in an optional OrderBy value that should default to DESC, and if set to false, should ORDER BY ASC. I'm not really sure how to do this ordering based off the input. Here is what I have currently:
CREATE DEFINER=`app`#`%` PROCEDURE `BLAH`(
pWithdrawalTransactionId INT,
pLimit INT,
pSortDescending TINYINT
)
BEGIN
DECLARE vLimit INT DEFAULT COALESCE(pLimit, 100);
DECLARE vSort TINYINT DEFAULT COALESCE(pSortDescending, 1);
SELECT
f.WithdrawalFulfillmentId, f.PaymentStatusId, f.PaymentProcessorId, f.PaymentTypeId, r.Amount, r.RequestedAmount, r.NativeAmount, r.NativeRequestedAmount, r.RefundTransactionId, r.UpdatedDate
FROM
FinOps.UserWithdrawalFulfillment f
INNER JOIN
FinOps.UserRefundTransaction r ON f.RefundTransactionId = r.RefundTransactionId
WHERE
f.WithdrawalTransactionId = pWithdrawalTransactionId
LIMIT
vLimit;
END
So the correct way to do this would be like this:
CREATE DEFINER=`app`#`%` PROCEDURE `BLAH`(
pWithdrawalTransactionId INT,
pLimit INT,
pSortDescending TINYINT
)
BEGIN
DECLARE vLimit INT DEFAULT COALESCE(pLimit, 100);
DECLARE vSort TINYINT DEFAULT COALESCE(pSortDescending, 1);
SELECT
f.WithdrawalFulfillmentId, f.PaymentStatusId, f.PaymentProcessorId, f.PaymentTypeId, r.Amount, r.RequestedAmount, r.NativeAmount, r.NativeRequestedAmount, r.RefundTransactionId, r.UpdatedDate
FROM
FinOps.UserWithdrawalFulfillment f
INNER JOIN
FinOps.UserRefundTransaction r ON f.RefundTransactionId = r.RefundTransactionId
WHERE
f.WithdrawalTransactionId = pWithdrawalTransactionId
ORDER BY CASE WHEN pSortDescending = 1 THEN WithdrawalFulfillmentId * -1 ELSE WithdrawalFulfillmentId END ASC
LIMIT
vLimit;
END

MySQL If Statement and Increment

I am having issues with a MySQL If statement that creates a group rank. here is the MySQL Statement:
SELECT EnCode, EnName, QuScore,
#scorerank := IF(#currathlete = EnCode, #scorerank + 1, 1),
#currathlete := EnCode
FROM ranking ORDER BY EnCode, QuScore DESC
It currently gives the following output
'1004277','Ashe','1628','1','1004277'
'1004277','Ashe','1309','1','1004277'
'1004277','Ashe','1263','1','1004277'
'1004277','Ashe','648','1','1004277'
'1004277','Ashe','645','1','1004277'
'1004277','Ashe','1628','1','1004277'
'1015934', 'Sabina', '544', '1', '1015934'
'1015934', 'Sabina', '455', '1', '1015934'
'1015934', 'Sabina', '276', '1', '1015934'
'1015934', 'Sabina', '216', '1', '1015934'
What it should be doing is incrementing each of the '1' numbers by one for each row that has the same code, and then starting from 1 again when it sees a different code number (1004277, then 1015934 in this case)
Any help is appreciated as i have followed a number of examples online using the above method but seem to hit the same issue a this point.
Try this way in stored Procedure:
drop PROCEDURE if EXISTS INCREMENTME;
create PROCEDURE INCREMENTME()
BEGIN
DECLARE OldEnNamevar VARCHAR(10) DEFAULT NULL;
DECLARE done INT DEFAULT FALSE;
DECLARE Encodevar VARCHAR(10);
DECLARE EnNamevar VARCHAR(10);
DECLARE QuScorevar VARCHAR(10);
DECLARE scorerankvar VARCHAR(10);
DECLARE currathalthletevar VARCHAR(10);
DECLARE countcode int(29) DEFAULT(1);
DECLARE counter int(20) default 0;
DECLARE get_cur CURSOR FOR select `Encode`,`EnName`,`QuScore`,`scorerank`,`currathalthlete` from tbl_ranking;
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
drop table if exists temp_temptable;
create TEMPORARY table temp_temptable(Encodevar VARCHAR(50) NULL,EnNamevar VARCHAR(50) NULL,QuScorevar VARCHAR(50) NULL,scorerankvar VARCHAR(50) NULL,currathalthletevar VARCHAR(50) NULL,recordCount int(10) null);
OPEN get_cur;
REPEAT
set counter = counter + 1;
FETCH get_cur INTO Encodevar,EnNamevar,QuScorevar,scorerankvar,currathalthletevar;
if (OldEnNamevar = EnNamevar) THEN
set countcode = countcode +1;
ELSE
if(counter=1) then
set countcode = 1;
ELSE
set countcode = 0;
end if;
end if;
if (OldEnNamevar != EnNamevar) THEN
set countcode = 1;
end if;
if(OldEnNamevar=NULL) then
set countcode = 1;
end if;
insert into temp_temptable (Encodevar,EnNamevar,QuScorevar,scorerankvar,currathalthletevar,recordCount) values(Encodevar,EnNamevar,QuScorevar,scorerankvar,currathalthletevar,countcode);
set OldEnNamevar = EnNamevar;
UNTIL done END REPEAT;
select * from temp_temptable;
drop temporary table if exists temp_temptable;
CLOSE get_cur;
END
call the procedure like this:
call INCREMENTME();
Here's the result:
You have to initialize your variables, otherwise they are null (at least at the beginning of the session, probably not anymore if you run it twice), and your query will give strange results. Try
SELECT EnCode, EnName, QuScore,
#scorerank := IF(#currathlete = EnCode, #scorerank + 1, 1),
#currathlete := EnCode
FROM ranking, (select #currathlete := '', #scorerank := 0) init
ORDER BY EnCode, QuScore DESC

mysql stored procedure group_concat returning null for select in cursor

I have a stored procedure where I'm looping through results in a cursor. The issue I'm having is the license_attributes value is always null when it shouldn't be. If I execute the select statement outside the stored procedure, or as a debug execute the select statement outside the cursor in the stored procedure, I get the results I'm expecting (not null)
This is the part of the select that is always returning null in the cursor:
(SELECT
CONCAT('{""',sf.Asset_Attribute__c.Type__c,'"": {',GROUP_CONCAT(
'""',sf.Asset_Attribute__c.Key__c,'"":""',LOWER(sf.Asset_Attribute__c.Value__c),'""'
),'}}')
FROM
sf.Asset_Attribute__c
WHERE
sf.Asset_Attribute__c.Asset__c = license_id
GROUP BY sf.Asset_Attribute__c.Asset__c) AS `license_attributes`
Here is the section of the stored proc:
GETCLOUDACCOUNTS:BEGIN
DECLARE no_more_cloud_accounts_records boolean DEFAULT FALSE;
DECLARE company VARCHAR(255) DEFAULT null;
DECLARE license_status VARCHAR(50) DEFAULT null;
DECLARE license_id VARCHAR(18) DEFAULT null;
DECLARE cloud_owner_email VARCHAR(255) DEFAULT null;
DECLARE entitlement_plan VARCHAR(255) DEFAULT null;
DECLARE role VARCHAR(500) DEFAULT null;
DECLARE is_trial BOOLEAN DEFAULT false;
DECLARE license_attributes VARCHAR(2000) DEFAULT null;
DECLARE zuora_account_id VARCHAR(100) DEFAULT '';
DECLARE zuora_account_number VARCHAR(50) DEFAULT null;
DECLARE zuora_account_status VARCHAR(50) DEFAULT null;
DECLARE zuora_account_last_invoice_date DATETIME DEFAULT null;
DECLARE has_active_subscriptions BOOLEAN DEFAULT false;
DECLARE cloud_accounts_cursor CURSOR FOR
SELECT
(SELECT `sf`.`Contact`.`CompanyName__c` FROM `sf`.`Contact` WHERE `sf`.`Asset`.`ContactId`=`sf`.`Contact`.`Id`) AS `company`,
`sf`.`License_Key_Association__c`.`License_Key_Status__c` AS `license_status`,
`sf`.`License_Key_Association__c`.`License_Key__c` AS `license_id`,
`sf`.`Asset`.`ContactEmail__c` AS `cloud_owner_email`,
(SELECT `sf`.`Contact`.`CloudEntitlementPlan__c` FROM `sf`.`Contact` WHERE `sf`.`Asset`.`ContactId`=`sf`.`Contact`.`Id`) AS `entitlement_plan`,
`sf`.`License_Key_Association__c`.`Role__c` AS `role`,
IF( (SELECT `sf`.`Product2`.`IsCommercial__c` FROM `sf`.`Product2` WHERE `sf`.`Product2`.`Id`=`sf`.`Asset`.`Product2Id`) = 0,true,false ) AS `is_trial`,
(SELECT
CONCAT('{""',sf.Asset_Attribute__c.Type__c,'"": {',GROUP_CONCAT(
'""',sf.Asset_Attribute__c.Key__c,'"":""',LOWER(sf.Asset_Attribute__c.Value__c),'""'
),'}}')
FROM
sf.Asset_Attribute__c
WHERE
sf.Asset_Attribute__c.Asset__c = license_id
GROUP BY sf.Asset_Attribute__c.Asset__c) AS `license_attributes`
FROM
`sf`.`License_Key_Association__c`
LEFT JOIN `sf`.`Asset`
ON `sf`.`License_Key_Association__c`.`License_Key__c` = `sf`.`Asset`.`Id`
JOIN `sf`.`Contact`
ON `sf`.`Contact`.`Id` = `sf`.`License_Key_Association__c`.`Contact__c`
WHERE
`sf`.`Contact`.`ExternalID__c`='someexternalidhere';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_cloud_accounts_records = true;
SELECT
(SELECT `sf`.`Contact`.`CompanyName__c` FROM `sf`.`Contact` WHERE `sf`.`Asset`.`ContactId`=`sf`.`Contact`.`Id`) AS `company`,
`sf`.`License_Key_Association__c`.`License_Key_Status__c` AS `license_status`,
`sf`.`License_Key_Association__c`.`License_Key__c` AS `license_id`,
`sf`.`Asset`.`ContactEmail__c` AS `cloud_owner_email`,
(SELECT `sf`.`Contact`.`CloudEntitlementPlan__c` FROM `sf`.`Contact` WHERE `sf`.`Asset`.`ContactId`=`sf`.`Contact`.`Id`) AS `entitlement_plan`,
`sf`.`License_Key_Association__c`.`Role__c` AS `role`,
IF( (SELECT `sf`.`Product2`.`IsCommercial__c` FROM `sf`.`Product2` WHERE `sf`.`Product2`.`Id`=`sf`.`Asset`.`Product2Id`) = 0,true,false ) AS `is_trial`,
(SELECT
CONCAT('{""',sf.Asset_Attribute__c.Type__c,'"": {',GROUP_CONCAT(
'""',sf.Asset_Attribute__c.Key__c,'"":""',LOWER(sf.Asset_Attribute__c.Value__c),'""'
),'}}')
FROM
sf.Asset_Attribute__c
WHERE
sf.Asset_Attribute__c.Asset__c = license_id
GROUP BY sf.Asset_Attribute__c.Asset__c) AS `license_attributes`
FROM
`sf`.`License_Key_Association__c`
LEFT JOIN `sf`.`Asset`
ON `sf`.`License_Key_Association__c`.`License_Key__c` = `sf`.`Asset`.`Id`
JOIN `sf`.`Contact`
ON `sf`.`Contact`.`Id` = `sf`.`License_Key_Association__c`.`Contact__c`
WHERE
`sf`.`Contact`.`ExternalID__c`=#p_externalId;
OPEN cloud_accounts_cursor;
CLOUDACCOUNTSLOOP: loop
fetch cloud_accounts_cursor into company, license_status, license_id, cloud_owner_email, entitlement_plan, role, is_trial, license_attributes;
IF is_trial = true THEN
SET has_active_subscriptions = true;
END IF;
SET zuora_account_id = `z`.`getZAccountId`(cloud_owner_email);
IF zuora_account_id IS NOT NULL THEN
SELECT `accountNumber`,`status`,`lastInvoiceDate` INTO zuora_account_number,zuora_account_status,zuora_account_last_invoice_date FROM zuora.Account WHERE id=zuora_account_id;
IF has_active_subscriptions = false THEN
SET has_active_subscriptions = (SELECT IF((SELECT COUNT(*) FROM `z`.`RatePlan`
RIGHT JOIN `z`.`ProductRatePlan` ON `z`.`RatePlan`.`productRatePlanId` = `z`.`ProductRatePlan`.`id`
LEFT JOIN `z`.`Subscription` ON `z`.`RatePlan`.`subscriptionId` = `z`.`Subscription`.`id`
WHERE
`z`.`ProductRatePlan`.`wowzaRatePlanCode__c` IN ( (SELECT `code` FROM `z`.`zCloudRatePlanCodes`) )
AND `z`.`Subscription`.`status` = 'Active'
AND `z`.`Subscription`.`accountId` = zuora_account_id ) > 0, true, false));
END IF;
END IF;
REPLACE INTO `sf`.`zCloudAccounts` (`user_email`,`company`,`license_status`,`license_id`,`cloud_owner_email`,`entitlement_plan`,`role`,`is_trial`,`attributes`,`zuora_account_id`,`zuora_account_number`,`zuora_account_status`,`zuora_account_last_invoice_date`,`has_active_subscriptions`) VALUES(#p_userEmail,company,license_status,license_id,cloud_owner_email,entitlement_plan,role,is_trial,license_attributes,zuora_account_id,zuora_account_number,zuora_account_status,zuora_account_last_invoice_date,has_active_subscriptions);
IF no_more_cloud_accounts_records THEN
CLOSE cloud_accounts_cursor;
LEAVE CLOUDACCOUNTSLOOP;
end if;
END LOOP CLOUDACCOUNTSLOOP;
END GETCLOUDACCOUNTS;
If I execute the full select stateout outside of GETCLOUDACCOUNTS block, I get the results I expect:
company, license_status, license_id, cloud_owner_email, entitlement_plan, role, is_trial, license_attributes
Test Company, Active, 02iq0000000jKgMAAU, myemail#email.com, Standard, Owner, 0, {""cloud"": {""cloud_num_247_t_streams"":""0"",""cloud_num_247_p_streams"":""0""}}
Test Company, Active, 02iq0000000xlBBAAY, otheremail#email.com, Standard, Admin;wcl_admin;wcl_support, 0, {""cloud"": {""cloud_num_247_t_streams"":""1"",""cloud_num_247_p_streams"":""1"",""test_attribute"":""true"",""api_access"":""true""}}
But the results inside the block show license_attributes as null:
company, license_status, license_id, cloud_owner_email, entitlement_plan, role, is_trial, license_attributes
Test Company, Active, 02iq0000000jKgMAAU, myemail#email.com, Standard, Owner, 0, null
Test Company, Active, 02iq0000000xlBBAAY, otheremail#email.com, Standard, Admin;wcl_admin;wcl_support, 0, null
Any help is greatly appreciated!
I suspect the issue is related to the procedure variable license_id.
The correlated subselect in the SELECT list includes
WHERE sf.Asset_Attribute__c.Asset__c = license_id
^^^^^^^^^^
Local variables take precedence over column references. Since license_id is declared as a variable within the code block,
DECLARE license_id VARCHAR(18) DEFAULT null;
the reference to license_id in the SELECT statement is a reference to that procedure variable.
Outside the code block, there likely is not a local variable named license_id. So that same SQL SELECT statement, that reference to license_id is not a reference to a variable, but a reference to a column.
I haven't traced through all of the logic, or the contents of license_id variable. But I suspect that explains the difference in the behavior observed with the statement, executed inside the code block vs outside the block.
You can COALESCE to take care of NULL values in your GROUP_CONCAT
COALESCE(`YourColumnName`,'')
You can also use a significantly different string to show you where the NULL value is coming from, so that you can then fix the query.
COALESCE(`YourColumnName`,'**UNEXPECTED NULL**')

SQL Adapter does not return result set when select after insert into the table

I am using SQL Adapter in IBM Worklight 6.1 and SQL Server 2008
Before insert the data to the table, I check whether the data is exist in the database or not.
If true, I select one column from the existed row.
Otherwise, I insert into the table and select one column of them.
The problem is when I insert and select the column, the adapter return only the insertion result.
{
"isSuccessful": true,
"updateStatementResult": {
"updateCount": 1
}
}
After I invoke the same query again, it return the result set.
{
"isSuccessful": true,
"resultSet": [
{
"ACCIDENTID": "A01407V00001"
}
]
}
The following is my table schema
CREATE TABLE accident
(
AccidentID varchar(13) NOT NULL,
Date varchar(12),
Time varchar(5),
Location varchar(150),
City varchar (20),
AssClaimNo varchar(17),
LitClaimNo varchar(17),
AssID varchar(9),
LitID varchar(9),
CLicenPlateNumber varchar(7),
PRIMARY KEY (AccidentID)
);
And this is my SQL statement
DECLARE #DATE VARCHAR(12) = '15 Jul 2014';
DECLARE #TIME VARCHAR(6) = '11:13';
DECLARE #ASSID VARCHAR(10) = '20140700a';
IF((SELECT COUNT(A1.ACCIDENTID)
FROM ACCIDENT A1
WHERE A1.DATE = #DATE AND A1.TIME = #TIME AND A1.ASSID = #ASSID) > 0)
BEGIN
SELECT A.ACCIDENTID
FROM ACCIDENT A
WHERE A.DATE = #DATE AND A.TIME = #TIME AND A.ASSID = #ASSID
END;
ELSE
BEGIN
DECLARE #ROWS INTEGER;
DECLARE #PREFIX VARCHAR(5) = '01407'
SET #ROWS = (SELECT COUNT(*)
FROM LITIGANT
WHERE LITID LIKE 'L'+ RIGHT(CAST(#PREFIX AS VARCHAR(5)),4) +'%')
SET #ROWS = #ROWS + 1;
DECLARE #LITID VARCHAR(9) = 'L' + RIGHT(CAST(#PREFIX AS VARCHAR(5)),4) + RIGHT('000'+CAST(#ROWS AS VARCHAR(4)),4)
INSERT INTO LITIGANT (LITID, LNAME, LEMAIL, LTELNUMBER, LDRIVERLICENSE, LCARBRAND, LCARCOLOR, LCARLICENPLATE, LINSNAME, LINSNUMBER)
VALUES(#LITID, 'Sample', 'sample#sample.com', '0839281938', '93810392', 'Volvo', 'Red', 'AB1234', '', '')
SET #ROWS = (SELECT COUNT(*)
FROM ACCIDENT
WHERE ACCIDENTID LIKE 'A'+#PREFIX+'%')
SET #ROWS = #ROWS + 1
DECLARE #ACCID VARCHAR(13) = 'A' + #PREFIX + 'V' + RIGHT('0000'+CAST(#ROWS AS VARCHAR(5)),5)
DECLARE #ACCCLAIM VARCHAR(16) = #ACCID + '-01'
DECLARE #LITCLAIM VARCHAR(16) = #ACCID + '-02'
INSERT INTO ACCIDENT (ACCIDENTID, DATE, TIME, LOCATION, CITY, ASSCLAIMNO, LITCLAIMNO, ASSID, LITID, CLICENPLATENUMBER)
VALUES( #ACCID, #DATE, #TIME, 'Bangkok', 'Bangkok', #ACCCLAIM, #LITCLAIM, #ASSID, #LITID, 'AR1234')
INSERT INTO CLAIM_STATUS
(CLAIMID, STATUS, ACCIDENTID)
VALUES(#ACCCLAIM, 0, #ACCID)
INSERT INTO CLAIM_STATUS
(CLAIMID, STATUS, ACCIDENTID)
VALUES(#LITCLAIM, 0, #ACCID)
SELECT #ACCID AS ACCIDENTID
END;
Is there a way to get the resultSet when insert into the table ?
Thank you for all suggestions and solutions.
You can get result set of inserted record by following format:
DECLARE #YourTableVariable TABLE(Column1 INT, Column2 INT)
INSERT INTO YourTable( Column1, Column2 )
OUTPUT Inserted.Column1, Inserted.Column2 INTO #YourTableVaribale
VALUES ( #Column1, #Column2)
Select * From #YourTableVariable