SQL Server Save Changes in Field after Update - stored-procedures

Good afternoon.
I am stuck in a stored procedure, lets say I have TableA and I want to Update to table A in the Bottom but Writing userwas useris in tableB
When I update values 1 by 1 I am able to save table B as it looks, but Im stuck when trying the update using where City = 'London'
Update [Table B]
SET UserIs = 'A8'
, UserWas = ( select User from [Table A] where City = 'London' ) **** ERROR
WHERE Id in (SELECT Id From [Table A] where City = 'London' )
( London comes from a Variable)
UPDATE [Table A]
SET USER = 'A8'
WHERE City = 'London'

Related

I have a column in table named "client_name".... i need to select column value from last row in my join query

i have table with column name policy_refer, client name and issue_date
policy_refer Client_Name issue_date(entry_date)
0001 Ajaz 01-Jan-2019
0001 Ajaz 05-Jan-2019
0001 Anita 10-Jan-2019
i want to select last update/insert client_name where policy_refer = 0001 , in my select/join query ....
select policy_master.CLIENT_NAME
,POLICY_INSURER_DETAIL.INSURER_NAME
,POLICY_INSURER_DETAIL.INSURER_BRANCH
,POLICY_INSURER_DETAIL.policy_number
,policy_master.policy_refer
,policy_master.POLICY_CLASS
,policy_master.POLICY_PRODUCT
,policy_master.P_ISSUE_DATE
,policy_master.EXPIRY_DATE
,sum(policy_master.TOTAL_SUMINSURED)
,sum(policy_master.GROSS)
,sum(policy_master.PERMIUM)
from POLICY_MASTER,POLICY_INSURER_DETAIL
where policy_master.policy_refer = POLICY_INSURER_DETAIL.POLICY_REFER
and POLICY_MASTER.POL_ID = POLICY_INSURER_DETAIL.POL_ID
and POLICY_MASTER.EXPIRY_DATE ='19-AUG-20'
and POLICY_MASTER.DOC_STATUS ='Posted'
group by POLICY_MASTER.policy_refer
,POLICY_INSURER_DETAIL.INSURER_NAME
,POLICY_INSURER_DETAIL.INSURER_BRANCH
,POLICY_INSURER_DETAIL.policy_number
,policy_master.policy_refer
,policy_master.EXPIRY_DATE
,policy_master.CLIENT_NAME
,policy_master.POLICY_CLASS
,policy_master.POLICY_PRODUCT
,policy_master.P_ISSUE_DATE;
One option is to find which one's the first (using analytic functions), and then fetch that row. For example:
select column_list_goes_here
from (
--> this is your current query, with the ROW_NUMBER addition
select all your columns here,
--
row_number() over (partition by policy_refer order by issue_date desc) rn
--
from your_tables
where ...
group by ...
--> end of your current query
)
where rn = 1
It appears the table you are talking about is the POLICY_MASTER table and you want the latest row (by ISSUE_DATE) for each policy.
Then you want to filter something like this:
select pm.CLIENT_NAME
,POLICY_INSURER_DETAIL.INSURER_NAME
,POLICY_INSURER_DETAIL.INSURER_BRANCH
,POLICY_INSURER_DETAIL.policy_number
,pm.policy_refer
,pm.POLICY_CLASS
,pm.POLICY_PRODUCT
,pm.P_ISSUE_DATE
,pm.EXPIRY_DATE
,sum(pm.TOTAL_SUMINSURED)
,sum(pm.GROSS)
,sum(pm.PERMIUM)
from (
SELECT *
FROM (
SELECT POL_ID,
CLIENT_NAME,
policy_refer,
POLICY_CLASS,
POLICY_PRODUCT,
P_ISSUE_DATE,
EXPIRY_DATE,
TOTAL_SUMINSURED,
GROSS,
PERMIUM,
ROW_NUMBER() OVER ( PARTITION BY policy_refer /*, pol_id */
ORDER BY ISSUE_DATE DESC ) AS rn
FROM POLICY_MASTER
WHERE EXPIRY_DATE = DATE '2020-08-19'
AND DOC_STATUS ='Posted'
)
WHERE rn = 1
) pm
INNER JOIN POLICY_INSURER_DETAIL pid
ON ( pm.policy_refer = pid.POLICY_REFER
AND pm.POL_ID = pid.POL_ID )
GROUP BY pm.policy_refer
,pid.INSURER_NAME
,pid.INSURER_BRANCH
,pid.policy_number
,pm.policy_refer
,pm.EXPIRY_DATE
,pm.CLIENT_NAME
,pm.POLICY_CLASS
,pm.POLICY_PRODUCT
,pm.P_ISSUE_DATE;
I guess you need the first row after sorting them in descending from issue date -
select policy_master.CLIENT_NAME
,POLICY_INSURER_DETAIL.INSURER_NAME
,POLICY_INSURER_DETAIL.INSURER_BRANCH
,POLICY_INSURER_DETAIL.policy_number
,policy_master.policy_refer
,policy_master.POLICY_CLASS
,policy_master.POLICY_PRODUCT
,policy_master.P_ISSUE_DATE
,policy_master.EXPIRY_DATE
,sum(policy_master.TOTAL_SUMINSURED)
,sum(policy_master.GROSS)
,sum(policy_master.PERMIUM)
from POLICY_MASTER,POLICY_INSURER_DETAIL
where policy_master.policy_refer = POLICY_INSURER_DETAIL.POLICY_REFER
and POLICY_MASTER.POL_ID = POLICY_INSURER_DETAIL.POL_ID
and POLICY_MASTER.EXPIRY_DATE ='19-AUG-20'
and POLICY_MASTER.DOC_STATUS ='Posted'
and rownum = 1
group by POLICY_MASTER.policy_refer
,POLICY_INSURER_DETAIL.INSURER_NAME
,POLICY_INSURER_DETAIL.INSURER_BRANCH
,POLICY_INSURER_DETAIL.policy_number
,policy_master.policy_refer
,policy_master.EXPIRY_DATE
,policy_master.CLIENT_NAME
,policy_master.POLICY_CLASS
,policy_master.POLICY_PRODUCT
,policy_master.P_ISSUE_DATE
ORDER BY P_ISSUE_DATE DESC;

Any way to improve the performance of this store procedure?

Any way to improve the performance of this store procedure?
For example combining both updates clauses in a unique statement (T-SQL).
BonosConvenio and CON_Convenio are almost 5K rows.
create table #resultados (
monto_deuda float
,Cuenta float
,Rut varchar(10)
,CodCONVENIO varchar(4)
,CONVENIO varchar(50)
,Bono varchar(15)
,MontoBono float
,ApellDeudor varchar(100)
)
INSERT INTO #resultados(Cuenta,monto_deuda,Rut,CodCONVENIO,CONVENIO,Bono,MontoBono,ApellDeudor)
select ATC_CTA_Correlativo, monto_deuda, RutDeudor, CodCONVENIO,'','',0,''
from CartaCobProgramasCONVENIO
where Nomina = #Nomina
UPDATE #resultados
SET Bono=bc.Bono,
MontoBono=bc.Monto
FROM BonosCONVENIO bc
WHERE bc.ATC_CTA_Correlativo=#resultados.Cuenta;
UPDATE #resultados
SET ApellDeudor=upper(rtrim(ltrim(Paciente.PAC_PAC_Nombre))
FROM BD_ENTI_CORPORATIVA..ATC_Cuenta Cuenta, BD_ENTI_CORPORATIVA..PAC_Paciente Paciente
WHERE Cuenta.ATC_CTA_Correlativo=#resultados.Cuenta AND Paciente.PAC_PAC_Numero = Cuenta.PAC_PAC_Numero
UPDATE #resultados
SET CONVENIO=c.CON_CON_Descripcio
FROM BD_ENTI_CORPORATIVA..CON_Convenio c
WHERE c.CON_CON_Codigo =#resultados.CodCONVENIO
SELECT * FROM #resultados ORDER BY Cuenta,Bono
End
Try this:
SELECT
ccpc.ATC_CTA_Correlativo Cuenta
, ccpc.monto_deuda
, ccpc.RutDeudor Rut
, ccpc.CodCONVENIO
, c.CON_CON_Descripcio CONVENIO
, bc.Bono
, bc.Monto MontoBono
, UPPER(RTRIM(LTRIM(Paciente.PAC_PAC_Nombre))) ApellDeudor
FROM
CartaCobProgramasCONVENIO ccpc
INNER JOIN
BonosCONVENIO bc ON
ccpc.ATC_CTA_Correlativo = bc.ATC_CTA_Correlativo
INNER JOIN
BD_ENTI_CORPORATIVA..ATC_Cuenta Cuenta ON
ccpc.ATC_CTA_Correlativo = Cuenta.ATC_CTA_Correlativo
INNER JOIN
BD_ENTI_CORPORATIVA..PAC_Paciente Paciente ON
Cuenta.PAC_PAC_Numero = Paciente.PAC_PAC_Numero
INNER JOIN
BD_ENTI_CORPORATIVA..CON_Convenio c ON
c.CON_CON_Codigo = ccpc.CodCONVENIO
WHERE Nomina = #Nomina;
If you have duplicate records because of the joins, it's because there are multiple values in the tables. Your original query (using an update) would overwrite and only show the last row's value. To work around this, you would probably want to have a GROUP BY and MIN, MAX, SUM or whatever.

How can this SQL subquery be expressed using Squeel/ActiveRecord?

I'm having a bit of brain fade today and can't figure out how I should express this SQL query correctly using ActiveRecord/Squeel/ARel:
SELECT `d1`.* FROM `domain_names` d1
WHERE `d1`.`created_at` = (
SELECT MAX(`d2`.`created_at`)
FROM `domain_names` d2
WHERE `d2`.`owner_type` = `d1`.`owner_type`
AND `d2`.`owner_id` = `d1`.`owner_id`
AND `d2`.`key` = `d1`.`key`
)
Any ideas?
Background: The DomainName model has a polymorphic owner as well as a "key" field that allows owners to have many different types of domain name. The query above fetches the latest domain name for each unique [owner_type, owner_id, key] tuple.
Edit:
Here's the same query using JOIN:
SELECT `d1`.* FROM `domain_names` d1
JOIN (
SELECT `owner_type`, `owner_id`, `key`, MAX(`created_at`) max_created_at
FROM `domain_names`
GROUP BY `owner_type`, `owner_id`, `key`
) d2
ON `d2`.`owner_type` = `d1`.`owner_type`
AND `d2`.`owner_id` = `d1`.`owner_id`
AND `d2`.`key` = `d1`.`key`
WHERE `d1`.`created_at` = `d2`.`max_created_at`

JPQL join tables doubles column names

I have multiple tables in a join and every table has a column ID. So in the resultig join there are a lot of ID columns. How I can access a specific ID column with the criteria API?
ParameterExpression<A> idParam = criteriaBuilder.parameter(A.class, PARAM_NAME);
Subquery<B> sq = query.subquery(B.class);
Root<B> root = sq.from(B.class);
Join<C, D> joinTogether = root.join("memberX").join("memberY");
sq.select(root);
sq.where(criteriaBuilder.and(criteriaBuilder.equal(joinTogether.get("id"), idParam), criteriaBuilder.equal(parentQuery.get("id"), root.get("id"))));
The problem is, that in the resulting SQL contains
SELECT 1 FROM E t6, B t5, C t4, D t3 WHERE ((( = paramName) AND (t0.ID = t5.ID)) AND (((t6.memberZ = t5.ID) AND (t4.ID = t6.memberX)) AND (t3.ID = t4.memberY))))
The table E (t6) is an additional join table between table B and C, t0 is the reference to the parent query. Instead t3.id = :paramName EclipseLink creates nothing just before the first equal-sign (paramName is the content of the constant PARAM_NAME). My idea is, that the "id" column could reference all tables and EclipseLink can not decide, which table I mean.
How I can change that?
Thank you
André

Uploading a Highscore - How to make it only visible to friends?

I'm wondering if there is a possibility when you upload your highscore you can compare your score with the one of your friends (if simpler, only selected contacts)?
And if so, could someone point me in the right direction, how to do it? I did not find anything useful about this on google.
As far as I pressume it should be possible, because apps like WhatsApp also let you choose specific contacts you want to send a message.
Related to that: Can I just use a/the cloud for uploading highscore or should I use my webspace?
I am not answering this specific to iOS/etc.
What you would typically do is expose a REST (or POX/POJSON - plain old XML or plain old JSON) service on your website that your application communicates with - it would be responsible for negotiating friendships, uploading high scores and retrieving high scores. This would either hit a database under your control or it would connect to a cloud server; there is no problem with either approach (Azure is a good option if you want to apply my SQL concepts).
Inside your database you would maintain a list of friends - this is a very simple structure to set up. Essentially you want two tables that look like the following:
CREATE TABLE [UserAccount]
(
[ID] BIGINT IDENTITY(1,1) PRIMARY KEY,
[Name] NVARCHAR(255),
)
CREATE TABLE [Friendship]
(
[User1] BIGINT, -- Primary key, FK to [UserAccount].[ID]
[User2] BIGINT, -- Primary key, FK to [UserAccount].[ID]
)
This would allow you to indicate friendships along the lines of:
User: ID = 1, Name = Joe
User: ID = 2, Name = Fred
Friendship: User1 = 1, User2 = 2
Friendship: User1 = 2, User1 = 1
You can then query friends using the following query:
SELECT [F1].[User2] AS [ID] FROM [Friendship] AS [F1]
WHERE [F1].[User1] = #CurrentUser
-- Check for symmetric relationship.
AND EXISTS
( SELECT 1 FROM [Friendship] AS [F2]
WHERE [F2].[User2] = [F1].[User1] AND [F2].[User1] = [F1].[User2] );
You could make that a TVF (Table Value Function) if your SQL variant supports them. Next you would create a high score table and a table to map it to users.
CREATE TABLE [Highscore]
{
[ID] BIGINT IDENTITY(1,1) PRIMARY KEY,
[Score] INT,
}
CREATE TABLE [UserHighscore]
{
[UserID] BIGINT, -- Primary key, FK to User.ID
[HighscoreID] BIGINT, -- Primary key, FK to Highscore.ID
}
Some sample data for this would be:
-- In this game you can only score over 9000!
Highscore: ID = 1, Score = 9001
Highscore: ID = 2, Score = 9005
Highscore: ID = 3, Score = 9008
UserHighscore: UserID = 1, HighscoreID = 1
UserHighscore: UserID = 1, HighscoreID = 2
UserHighscore: UserID = 2, HighscoreID = 3
You can then query for your friends' highscores:
SELECT TOP(10) [U].[Name], [H].[Score] FROM [Friendship] AS [F1]
LEFT INNER JOIN [User] AS [U] ON [U].[ID] = [F1].[User2]
LEFT INNER JOIN [HighscoreUser] AS [HU] ON [HU].[UserID] = [F1].[User2]
LEFT INNER JOIN [Highscore] AS [H] ON [H].[ID] = [HU].[UserID]
WHERE [F1].[User1] = #CurrentUser
-- Check for symmetric relationship.
AND EXISTS
( SELECT 1 FROM [Friendship] AS [F2]
WHERE [F2].[User2] = [F1].[User1] AND [F2].[User1] = [F1].[User2] )
ORDER BY [H].[Score] DESC;
That query would give the top 10 score your friends; giving you their name and score.

Resources