Very new SQL Server, am using SQL server 2008. I have two tables, Table A and Table B
I want to update Table A with the count of a matching strings of Table B. Here is what I came up by declaring a static varchar. I would like it to do it in a procedure for all Records in Table A anytime a record is inserted/updated in Table B.
TABLE A: **PO**, Count, Closed Table B: **LD**
24A, 0, 0, 24A-1
25A, 0, 0, 24A-2
26A, 0, 0, 25A-3
26A-1
26A-2
Code I tried:
Declare @POTableA AS VARCHAR(15)
SET @POTableA = '24A'
Update TABLE A
SET TableA.Count =(Select Count(*) AS 'Count_LD' FROM TABLE B
WHERE TableB.LD LIKE '%'+@POTableA+'-%')
FROM TABLE B WHERE TABLEA.PO LIKE '%'+@POTableA+'%'
Current result:
TABLE A: **PO**, Count, Closed Table B: **LD**
24A, 2, 0, 24A-1
25A, 0, 0, 24A-2
26A, 0, 0, 25A-3
26A-1
26A-2
Desired result:
TABLE A: **PO**, Count, Closed Table B: **LD**
24A, 2, 0, 24A-1
25A, 1, 0, 24A-2
26A, 2, 0, 25A-3
26A-1
26A-2
While I’m not sure why you need to keep the count stored in table A – you can always determine this count at runtime, then you don’t have to use triggers etc. to maintain that information (which is redundant). But here is a demonstration using table variables about how such an update with an aggregate could be achieved (there are other ways, likely).
Results:
Now if you need to do this in a trigger, it would be something like:
You might want to modify one of those lines to:
But since you only gave three sample values in the question, and they were all the exact same format, it’s tough to tell what your true data set looks like.