order by desc didnt not arrange my data - c#

once there are new data insert to my DB my rcount will increase by 1, what am i trying to do is to display latest inserted record to users, but i cant get my expected result
rCount in my datebase
1
2
3
4
5
output
5
4
3
1
2
expected output
5
4
3
2
1
"SELECT *, ROW_NUMBER() OVER (ORDER BY rCount DESC) AS 'RowNumber'
FROM [MovieListTable]"

Instead of using the row number you should introduce a numeric primary key (i.e. Id) and make it an Identity column. Now you can just select the row that has the maximum Id value:
select top 1 * from MovieListTable order by Id desc
Or to get all rows:
select * from MovieListTable order by Id desc

Related

Custom Autogenerated Column in SQL Server

I want to generate a unique PrescriptionNo for each of the Prescription based on the shopid.
I have tried the following way
id PrescriptionNo Shopid Amount
1 PRES001 2 100
2 PRES002 2 200
3 PRES001 1 100
4 PRES003 2 200
select top 1 'PRES' + right('000' + CAST(ROW_NUMBER() over (order by id) + 1 AS VARCHAR(3)),3)
from prescription
where shopid = 2
order by id desc
Try this:
create table #tmp1 (id int, prescriptionno varchar(10), shopid int, amount int);
insert into #tmp1 values (1,'PRES001',2,100);
insert into #tmp1 values (2,'PRES002',2,200);
insert into #tmp1 values (3,'PRES001',1,100);
insert into #tmp1 values (4,'PRES003',2,200);
select 'PRES' + RIGHT(concat('000',ISNULL(max(right(prescriptionNo,3)),0)+1),3)
from #tmp1
where shopid = 3
=> Returns 'PRES0001'
select 'PRES' + RIGHT(concat('000',ISNULL(max(right(prescriptionNo,3)),0)+1),3)
from #tmp1
where shopid = 2
==> Returns 'PRES0004'
By using just max() allows you to use ISNULL(..,0).

Assigning even number of FK's in a table based on an even number

I have two tables where I have a situation like this:
Table1
column1
column2
column3
column4
column5
Table 2 structure:
Table2
Col1
Col2
Col3
Table1FK
My table 1 currently has 3 records inside it, and the table 2 shall contain more records than table 1 (one to many relationship between these two). I want to assign an even number of records from Table 2 to table 1 FK's.
For example:
If table 2 has 20 records and if table 1 has 3 records
I will divide these two and get an even number, 6.66 in this case.
So the table1 PK's should be assigned like
6-6-8
or
7 7 6 (this one is more even)
And then table 1 PK under identity let's say 1500 would have 7 of it's corresponding FK's in table 2 , 7 for Identity 1501 , and 6 for identity 1502
Starting point is that I should divide these:
var evenAmountOfFKs = table2.Count()/table1.Count();
What would be the next step here, and how could I achieve this ?
Can someone help me out?
No matter how weird the requirement seems, the math was fun.
At first, we have to determine the number of parents:
DECLARE #NoParents int = (SELECT COUNT(*) FROM Table1);
Both parents and children can be numbered starting with 0, and then a child can be assigned to parent x with x = ChildNo % #NoParents:
DECLARE #NoParents int = (SELECT COUNT(*) FROM Table1);
WITH
Parents AS (
SELECT column1, column2, column3, column4, column5,
ROW_NUMBER() OVER(ORDER BY column1)-1 AS ParentNo
FROM Table1
),
Children AS (
SELECT Col1, Col1, Col1,
(ROW_NUMBER() OVER(ORDER BY Col1)-1) % #NoParents AS ParentNo
FROM Table2
)
SELECT p.column1, p.column2, p.column3, p.column4, p.column5, c.Col1, c.Col1
FROM Parents p
INNER JOIN Children c ON p.ParentNo = c.ParentNo;
This will produce an "even" assignment.

Get data from SQLServer in ASC order

I have a table with column name id and value. While data is being saved in sql server database, it sorts itself in random order, i.e id value 1,2,3,4,5,6,7,14,15,16,17,8,9,10 and likewise.
I need to retrieve data in 4 groups with each having 11 data in asc id order,
that is,
Group 1: 1-11
Group 2 : 12-22
Group 3 : 23-33
Group 4 : 33-44
I have tried query
Group 1:select top(11) * from tblCode order by id ASC
Group 2:SELECT top(22)* FROM tblCode except select top(11) * from tblCode order by id ASC
Group 3:SELECT top(33)* FROM tblCode except select top(22) * from tblQRCode order by id ASC
group 4:SELECT top(44)* FROM tblCode except select top(33) * from tblCode order by id ASC
What my problem is since data are sorted randomly while saving them into database, they are retrieved randomly.
Below is the screenshot of how my data are saved in database.
help me select data as above mentioned group.
Use OFFSET and FETCH rather than TOP.
E.g. Group two would be:
select *
from tblCode
order by id ASC
offset 11 rows
fetch next 11 rows only
Complete repro script:
declare #t table (ID int not null, Value varchar(93) not null);
;With Numbers as (
select ROW_NUMBER() OVER (ORDER BY so1.object_id) as n
from sys.objects so1,sys.objects so2,sys.objects so3
)
insert into #t (ID,Value)
select n,'PEC-' + CONVERT(varchar(93),n)
from Numbers
where n between 1 and 1000
select *
from #t
order by id ASC
offset 11 rows
fetch next 11 rows only
Result:
ID Value
----------- ---------
12 PEC-12
13 PEC-13
14 PEC-14
15 PEC-15
16 PEC-16
17 PEC-17
18 PEC-18
19 PEC-19
20 PEC-20
21 PEC-21
22 PEC-22
This also get your desired results. For other queries change 33 with other values, now it get values from 33 to 22.
WITH t AS
( SELECT ROW_NUMBER() OVER (ORDER BY id) AS row_num, *
FROM tblCode )
SELECT TOP 11 *
FROM t
WHERE row_num > 33
Try this,
select * from Table Name Order by ID
I hope I am not misunderstand:
--Group 1
SELECT *
FROM tblCode
WHERE id >= 1
AND id <= 11
ORDER BY id ASC
--Group 2
SELECT *
FROM tblCode
WHERE id >= 12
AND id <= 22
ORDER BY id ASC
--Group 3
SELECT *
FROM tblCode
WHERE id >= 23
AND id <= 33
ORDER BY id ASC
You can also save the increments in variable. Maybe something like this (i.e) you send param group no 3:
--Group 3
SELECT #Group = 3 --just for sample, param should sent From application
SELECT #lastIndex = 3*11
SELECT #indexStart = #lastIndex - 10
SELECT *
FROM tblCode
WHERE id >= #indexStart
AND id <= #lastIndex
ORDER BY id ASC

Recursively update values based on rows parent id SQL Server

I have the following table structure
| id | parentID | count1 |
2 -1 1
3 2 1
4 2 0
5 3 1
6 5 0
I increase count values from my source code, but i also need the increase in value to bubble up to each parent id row until the parent id is -1.
eg. If I were to increase count1 on row ID #6 by 1, row ID #5 would increase by 1, ID #3 would increase by 1, and ID #2 would increase by 1.
Rows also get deleted, and the opposite would need to happen, basically subtracting the row to be deleted' value from each parent.
Thanks in advance for your insight.
I'm using SQL Server 2008, and C# asp.net.
If you really want to just update counts, you could want to write stored procedure to do so:
create procedure usp_temp_update
(
#id int,
#value int = 1
)
as
begin
with cte as (
-- Take record
select t.id, t.parentid from temp as t where t.id = #id
union all
-- And all parents recursively
select t.id, t.parentid
from cte as c
inner join temp as t on t.id = c.parentid
)
update temp set
cnt = cnt + #value
where id in (select id from cte)
end
SQL FIDDLE EXAMPLE
So you could call it after you insert and delete rows. But if your count field are depends just on your table, I would suggest to make a triggers which will recalculate your values
You want to use a recursive CTE for this:
with cte as (
select id, id as parentid, 1 as level
from t
union all
select cte.id, t.parentid, cte.level + 1
from t join
cte
on t.id = cte.parentid
where cte.parentid <> -1
) --select parentid from cte where id = 6
update t
set count1 = count1 + 1
where id in (select parentid from cte where id = 6);
Here is the SQL Fiddle.

Insert Multiple Rows to table after select and change Values rows

:)
i have a table the Includ any row.
Names Rows my Table is:
ID_ImgPhoto(PK),IDPhoto(FK),Title,Small,Larg,AddedDate,AddedIp,Status.
i want read at the DataReader in asp.net and change string the String.replace() many Values Small And Larg row in my table.
i want Insert Multiple Rows to table after select and change The Same Values rows.
i want select many row With a Condition.
My select Code Is:
ALTER Procedure [dbo].[sp_Tbl_ImagePhotoGraphy_SelectRow]
#IDPhoto int
As
Begin
Select
[ID_ImgPhoto],
[IDPhoto],
[Title],
[Small],
[Larg],
[AddedDate],
[AddedIp],
[Status]
From Tbl_ImagePhotoGraphy
Where
[IDPhoto] = #IDPhoto
End
i Want changed value many rows after the give Value #IDPhoto And select Many Row my table and FOR EXAMPLE :
/*OLD DATA*/
ID_ImgPhoto IDPhoto Small Larg
1 1 OLD/1S.jpg OLD/1L.jpg
2 1 OLD/2S.jpg OLD/2L.jpg
3 1 OLD/3S.jpg OLD/3L.jpg
4 2 Oldsmall/1S.jpg OldLarg/1L.jpg
5 2 Oldsmall/1S.jpg OldLarg/1L.jpg
5 2 Oldsmall/1S.jpg OldLarg/1L.jpg
5 2 Oldsmall/1S.jpg OldLarg/1L.jpg
____________________________________________________________________
/*NEW DATA Afetr Select And Chnage Rows Value*/
ID_ImgPhoto IDPhoto Small Larg
1 1 NEW/1S.jpg NEW/1L.jpg
2 1 NEW/2S.jpg NEW/2L.jpg
3 1 NEW/3S.jpg NEW/3L.jpg
4 2 Oldsmall-2/1S.jpg OldLarg-2/1L.jpg
5 2 Oldsmall-2/1S.jpg OldLarg-2/1L.jpg
5 2 Oldsmall-2/1S.jpg OldLarg-2/1L.jpg
5 2 Oldsmall-2/1S.jpg OldLarg-2/1L.jpg
I FIND THIS Sulotion.:)
UPDATE yourtable set small=replace(small,'OLD/','NEW/'),larg=replace(larg,'OLD/','NEW/')

Categories

Resources