Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have inserted 4 records into table1, and then 5 records and then 3 records.
Now I want to pick up last 3 records or say any number of records but inserted at last. How I will get those ?
Actually scenario is that in gridview 1 user would select say 3 records by help of checkbox field and then these 3 records will be inserted in to table1 and then store procedure will pick these last inserted 3 reocrds and assign it to RDLC report. All things are done but just don't know how to pick last inserted any number of records.
By definition, a table is an unordered set of rows. There is no way to ask SQL Server which row was inserted last unless you are doing so in the same batch as the insert. For example, if your table has an IDENTITY column, you can say:
INSERT dbo.table(column) values (...)
SELECT SCOPE_IDENTITY();
But that too will give you the last first identity column.
What you can do here is that you can take the help of timestamp and define that in a separate column of the table.
ALTER TABLE dbo.table ADD DateInserted DEFAULT CURRENT_TIMESTAMP;
Define stored procedure with the #lastrows count that you will store in your service layer to call.
CREATE PROC sp_GetLastInsertedRows(#lastrows int)
AS
;WITH x AS (SELECT *, r = ROW_NUMBER() OVER (ORDER BY DateInserted DESC)
FROM dbo.table)
SELECT * FROM x WHERE r <= N;
This way you get the last N number of rows inserted in the last transaction.
you can use below menioned query
SELECT column_name FROM table_name
ORDER BY column_name DESC
LIMIT 3;
Okay, so you're going to need something a bit more flexible. Right now you may have just one user, and right now you may be running the report immediately after executing the INSERT statements, but what you really need to know is what rows are new since the last time you looked.
One good way of doing this is adding a DATETIME NULL field to the row; let's call it processed_date. This field will be updated by the stored procedure that picks them up for the report. Something like this:
SELECT * FROM tbl1
INTO #report_tbl
WHERE processed_date IS NULL
UPDATE tbl1
SET processed_date = GETDATE()
WHERE id_field IN (
SELECT id_field
FROM #report_tbl
)
Now you are sure to pick up the rows that "haven't been looked at."
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a database table which has columns with values 1 till 999
But it has some spaces e.g. 1,2,3,4,5,6,11,15 etc...
What would be the best to get the "next number" from this table?
Thanks in advance for your help
one way to do this is to get for every row the prior row, and then check where you are making a step.
This will not perform great, and it is NOT SAFE when more then 1 user is adding new rows !
declare #t table (number int)
insert into #t values (1), (2), (3), (4), (5), (6), (11), (12)
select top 1
(select top 1 t2.number + 1 from #t t2 where t2.number < t.number order by t2.number desc) as prior
from #t t
where number <> (select top 1 t2.number + 1 from #t t2 where t2.number < t.number order by t2.number desc)
order by t.number
The result would be 7
Another option is this
select top 1
t.number + 1
from #t t
left join #t t2 on t.number = t2.number - 1
where t2.number is null
order by t.number
This method might even be faster then the solution of Robin
EDIT
As Daniel pointed out in a comment, this will never return 1 in case the gap happens to be the first row.
To fix this, we can retrieve a value for the first missing row, and add it to our result by use of a union.
select top 1 number
from ( select top 1
t.number + 1 as number
from #t t
left join #t t2 on t.number = t2.number - 1
where t2.number is null
union
select 1 as number
from #t t
where not exists (select 1 from #t t3 where t3.number = 1)
) t
order by t.number
Since the extra query can only retrieve exact one row by an index, this should not affect performance much
You can use a CTE to generate the numbers and then get the first one that does not match with a record....
This work fine as you mentioned that it is not a large table
I have a datatable which has columns with values 1 till 999
Regard the other answers, both are too much faster than this with large tables, but none of them will return the correct value (1) if your input starts on 2 or greater.
I don't know the purpose of this request, but be aware that calculating values this way two users working at same time can get the same value. It can be an issue specially if you want to use this value to be part of a primary key or unique index
;with numbers as (
SELECT 1 as nrstart, MAX(yourcolumn) as nrend FROM yourTable
UNION ALL
SELECT nrstart+1, nrend FROM numbers
WHERE nrstart <= nrend
)
SELECT TOP 1 nrstart
FROM numbers
WHERE NOT EXISTS (SELECT 1 FROM yourTable WHERE yourcolumn = numbers.nrstart)
ORDER BY nrStart
OPTION (MAXRECURSION 0);
You want the first number, where that number plus one is not in the table.
SELECT TOP 1 (Number + 1) FROM myTable a WHERE NOT EXISTS
(SELECT * FROM myTable b WHERE b.Number = a.Number + 1)
ORDER By Number
As mentioned in various comments, this sort of thing should be done in a transaction if there's any risk of a second user filling the gap while the first is looking for it.
I am working on a desktop application in C#. I am very new to SQL Server.
First of all I would like apologize for the question I am asking may be relevant to the questions asked before on this topic, but I searched on the internet and did not find any answer for the problem.
There is a table in my database named BillingTemp. Columns are
Bill No, Package, Type, DiscPer, TotalAmt, BillDate, TaxAmt
BillNo may repeat as there are multiple entries in a specific bill.
Now on a button click, TotalAmt and type values in this table should be updated in only first row of a table as per my logic in the code.
How can I do this? Can anyone suggest query for this?
Try this
;WITH TOP1 AS
(
SELECT TOP 1 *
FROM TABLE
WHERE BillNo = #BillNo
ORDER BY ID -- I assume you always want to update the record created first
)
UPDATE TOP1 SET TotalAmt =#TotalAmt , type = #type
I have a table wherein I want to update a rows individually:
Transaction ID EmpID START END LOGDATE
1 1 8:32:32 NULL 7/25/2016
2 2 9:02:10 NULL 7/25/2016
3 3 9:00:56 NULL 7/25/2016
4 3 9:42:00 NULL 7/26/2016
5 2 10:58:00 NULL 7/26/2016
6 1 9:23:00 NULL 7/26/2016
If I use this:
UPDATE EmpLog SET ShiftEnd = '09:00:00' WHERE EmpID = 1 and CONVERT(date, EmpLog.LogDate) = CONVERT(date, GETDATE())
I can only update the specific row within the day, but since I need to be able to account for overtime, it can't be.
How do I update a specific row to update the END column for a specific transaction with C#?
Basically, the layout of my C# program is that a user must input his EmpID, and press 'START' or 'END'. but the 'END' part is tricky. I ended up updating all rows and losing previous data.
How do I update a specific row with the latest transaction ID for each specific employee? Sorry If i'm confusing.
I read your question like this:
I want to update the last entry for a specific employee
As long as the transaction id will increase for every entry, you could do something like this:
UPDATE EmpLog
SET ShiftEnd = '09:00:00'
WHERE EmpID = 1 AND [Transaction ID] =
(SELECT MAX([Transaction ID]) FROM EmpLog WHERE EmpID = 1)
Read this similiar question:
Is it possible to use MAX in update statement using sql?
This is for MS SQL Server mainly, but I think you can easily translate it to mysql. There may be an even better way in mysql.
Downside with this solution: You have to make an extra select in your update, which will be slower, but for this example if think it should do fine.
Im working on database synchronization in my app. It means I have 5 databases, but:
only in first database product could be added/removed/modified
this first database saving information about added/removed/modified product to table (with flag 1/2/3 as add/edit/remove and productID)
so first database generates INSERT script from SELECT, for example:
in my product_changes table (addedRemovedEdited INT, productID INT) I have information:
1, 15 (1 - flag means product with ID = 15 was added), or
2, 15 (2 - flag means product with ID = 15 was edited) etc.
Now using this information I can create script - and there is problem.
At this momment im creating scripts like:
SELECT (col1, col2, col3,...) FROM Product_Category;
string query = "INSERT INTO Table VALUES (#a,#b,#c)...";
SELECT (col1,col2,col3,...) FROM Product_price;
query += "INSERT INTO .......";
And I need to do it foreach tables which contains information about one single products. So for 10 products I'll have 10 * 12 (12 because there is ~12 tables about one product) blocks of code like INSERT INTO Table 1(....); INSERT INTO TABLE2(....).
Problem is also that, all data need to have same ID in every databases - so I'm using ##identity and put it into insert query. It has to be this way, because product with ID = 10 with name 'Keyboard' in mainDB = product with ID = 10 in DB10.
And the question - maybe some of you know any better (becouse that one is not so good) solution how can I create those scripts? Like query, which will take all information from my string[] a = {"Product", "Product_price", "Product_category"} tables and generate INSERT queries but - most important - where I can add ##identity.
#EDIT: I forgot. I found that solution: how i can generate programmatically "insert into" data script file from a database table?
Well, it does generate scripts, but with auto-incremented ID. And I need to add information in right order (as middle tables) for example:
INSERT INTO Product(.....) VALUES (...);
SET #pID = ##identity FROM Product;
INSERT INTO Price (priceID,.....) VALUES (...);
SET #prID = ##identity FROM Price;
INSERT INTO Product_price (priceID, productID,...) VALUES (#prID, #pID)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to make a search function for sql database , and how to get time when info from a table was edited?
I have a table with 3 columns : Name,Age,Birthday,date
Also there's a option on my asp.net website page on each line of columns an edit button so I can edit the text from name,age,birthday.
How can I make let's say when I edit the text from name column , the date column will have the Value : "Name was edited : date/time" and so on .
Would someone help me ? I've tried this since 4 days ago and I couldn't find something.
I'm using SQL database 2008,
Thanks
Well,
follow the example. (Remember, we can do this different )
First of all, you have to add a new column to your table
Alter table INFORMATION add LastUpdate datetime null
Then you create the Trigger (take care, you have to declare the variable Name like your table)
Create TRIGGER trig_Information
ON Information
FOR UPDATE
AS
BEGIN
declare #Name as varchar(100) /*Look up your column type*/
select #Name = i.Name from Inserted i
update Information set LastUpdate = getdate() where Name = #Name
END
So, everytime someone update any register of this table, the trigger will update the field LastUpdate with the date/time of the operation.
MS. If your table has more than one PK, specify at the where clause.
see ya