get previous row id using stored procedure - sql

My requirement like this:
I have to fetch a row from table "A". Now I have to loop through all the rows and get the values from the ID column. If I get ID = 5 then I want to execute some stored procedure through which I get the previous id row from some table "B". Like
select * from table b where ID = 4
Buy my question is: if someone deleted that row from the database (e.g. some user deleted the rows with id 3 and 4) - then how can I get the row with id = 2 from the database?
Please give me some sql stored procedure to get previous id record from table.

Hard to understand exactly what it is your looking for - something like this maybe??
CREATE PROCEDURE dbo.FetchPreviousRow #ID INT
AS BEGIN
SELECT TOP 1 ID, (other columns.....)
FROM dbo.TableB
WHERE ID < #ID
ORDER BY ID DESC
END
This will select the row with the biggest ID less than the #ID you pass in, so:
EXEC dbo.FetchPreviousRow #ID = 5
will return the row with ID = 4 - if it exists. Otherwise, it will return the row with ID = 3 - if it exists. Otherwise the row with ID = 2 - and so on....

The following query should get it for you:
select max(ID) from YourTable where ID < #YourID
#YourID is a variable containing your recently inserted ID

How about selecting all ID's less than 5 and sorting them by ID. The first result then would be the one you want.

Related

Select records from a specific key onwards

I have a table that has more than three trillion records
The main key of this table is guid
As below
GUID Value mid id
0B821574-8E85-4FB7-8047-553393E385CB 4 51 15
716F74B0-80D8-4869-86B4-99FF9EB10561 0 510 153
7EBA2C31-FFC8-4071-B11A-9E2B7ED16B2B 2 5 3
85491F90-E4C6-4030-B1E5-B9CA36238AE2 1 58 7
F04FA30C-0C35-4B9F-A01C-708C0189815D 20 50 13
guid is primary key
I want to select 10 records from where the key is equal to, for example, 85491F90-E4C6-4030-B1E5-B9CA36238AE2
You can use order by and top. Assuming that guid defines the ordering of the rows:
select top (10) t.*
from mytable t
where guid >= '85491F90-E4C6-4030-B1E5-B9CA36238AE2'
order by guid
If the ordering is defined in an other column, say id (that should be unique as well), then you would use a correlated subquery for filterig:
select top (10) t.*
from mytable t
where id >= (select id from mytable t1 where guid = '85491F90-E4C6-4030-B1E5-B9CA36238AE2')
order by id
To read data onward You can use OFFSET .. FETCH in the ORDER BY since MS SQL Server 2012. According learn.microsoft.com something like this:
-- Declare and set the variables for the OFFSET and FETCH values.
DECLARE #StartingRowNumber INT = 1
, #RowCountPerPage INT = 10;
-- Create the condition to stop the transaction after all rows have been returned:
WHILE (SELECT COUNT(*) FROM mytable) >= #StartingRowNumber
BEGIN
-- Run the query until the stop condition is met:
SELECT *
FROM mytable WHERE guid = '85491F90-E4C6-4030-B1E5-B9CA36238AE2'
ORDER BY id
OFFSET #StartingRowNumber - 1 ROWS
FETCH NEXT #RowCountPerPage ROWS ONLY;
-- Increment #StartingRowNumber value:
SET #StartingRowNumber = #StartingRowNumber + #RowCountPerPage;
CONTINUE
END;
In the real world it will not be enough, because another processes could (try) read or write data in your table at the same time.
Please, read documentation, for example, search for "Running multiple queries in a single transaction" in the https://learn.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql
Proper indexes for fields id and guid must to be created/applied to provide performance

set value column where id is in the other table

I am trying to modify a table of my taking the id of another table being that this other table is with another column, taking only if the data of that column is 2, take the ID of that column and use in the one that I want to change, example:
UPDATE QuestData SET RepeatFinish = 100000
WHERE QuestID =
(
SELECT * FROM Quest WHERE QuestID = 2
);
But QuestData have so much data and table Quest too, how can i make this?
UPDATE QuestData SET RepeatFinish = 100000
WHERE QuestID in
(
SELECT id FROM Quest WHERE QuestID = 2
);
Change the id in select by yours. when using the in with an other request the select must return a one field that will be used in IN, you are using * so we don't know with what we should compare the QuestID

Single SQL Query to validate input values

I have written a Stored procedure which has three argumets
#UserID1 BIGINT
#UserID2 BIGINT
#UserID3 BIGINT
What I want to achieve is to write a single SQL query against table dbo.aspnet_UsersInRoles column ID so that #UserID1, #UserID2, #UserID3 are present in ID column of dbo.aspnet_UsersInRoles.
For example, I have received three values in variables and I want to confirm they are part of Id column. i.e. ID column of table has values 1,2,3,4,5,6,7,8,9,10 and UserID1 is 2, UserID2 is 5 and UserID3 is 7. So it should give true else false.
I can implement using three different queries but I am not getting any clue to do it in a single query.
You should be able to use something like this:
SELECT CASE WHEN SUM( CASE
WHEN #UserID1 = ID THEN 1
WHEN #UserID2 = ID THEN 1
WHEN #UserID3 = ID THEN 1
ELSE 0
END ) = 3 THEN 1 ELSE 0 AS [AllThree]
FROM aspnet_UsersInRoles
(untested code)
...assuming that the ID column is unique. If all three IDs are in the table, then you should end up with a summed value of 3. This will allow you to process the table in a single pass, but you don't get the advantages of index lookups like you get in Upendra's answer.

SQL Query Create isDuplicate Column with IDs

I have a SQL Server 2005 database I'm working with. For the query I am using, I want to add a custom column that can start at any number and increment based on the row entry number.
For example, I start at number 10. Each row in my results will have an incrementing number 10, 11, 12, etc..
This is an example of the SELECT statement I would be using.
int customVal = 10;
SELECT
ID, customVal++
FROM myTable
The format of the above is clearly wrong, but it is conceptually what I am looking for.
RESULTS:
ID CustomColumn
-------------------
1 10
2 11
3 12
4 13
How can I go about implementing this kind functionality?
I cannot find any reference to incrementing variables within results. Is this the case?
EDIT: The customVal number will be pulled from another table. I.e. probably do a Select statement into the customVal variable. You cannot assume the the ID column will be any usable values.
The CustomColumn will be auto-incrementing starting at the customVal.
Use the ROW_NUMBER ranking function - http://technet.microsoft.com/en-us/library/ms186734.aspx
DECLARE #Offset INT = 9
SELECT
ID
, ROW_NUMBER() OVER (ORDER BY ID) + #Offset
FROM
Table

Compare Combinations in SQL Server

I need to compare two attributes in a table as a single combination.
Basically I have this table in my database with these attributes and some sample data.
Rights => RoleID,SectionID,RightID
1 2 3
1 3 5
1 5 7
2 3 5
2 1 6
so I want to pass the sectionID and RightID information belonging to a certain roleID as input in my stored procedure and return the ROleID. For example when I pass the combinations (3,5) and (1,6) my stored procedure should return RoleID 2. If there is no exact match with the combinations I pass as my input, it shouldn't return anything.
Any help in this regard is highly appreciated.
I haven't tested this but you might able to use this or amend as appropriate. The idea is that you put the joined values into temp column then use that as basis for calling the procedure. If that fails you might want to add another column to your table with the joined roleid and sectioned?
CREATE PROCEDURE GETRIGHTS
(
#param varchar(10)
)
AS
SELECT * INTO #RIGHTS FROM TABLENAME
ALTER TABLE #RIGHTS ADD JOINEDVALUES INT
SELECT #RIGHTS.JOINEDVALUE = (SELECT ROLEID + ',' + SECTIONID FROM TABLENAME WHERE #RIGHTS.JOINEDVALUE = #PARAMS)