How to set limit table row in SQL Server?
I want to set limit of my table rows to 100 rows only.
So when the table have more than 100 rows, I want to delete first row then add new row to last row (100).
How can I do this?
One thing that i can assure you..
Create a trigger that if > 100 then delete first record record.
see here as your guide.
I think you hv to do two things
i) Create Trigger
declare #MaxRowLimit int=5
declare #t table(col1 int)
insert into #t values(1),(2),(3),(4),(5)
insert into #t VALUES(12)
;With CTE as
(
select top (#MaxRowLimit) col1
from #t t1
order by t1.col1 desc
)
,CTE1 as(
select * from #t t
where not exists
(select col1
from cte t1 where t.col1=t1.col1
)
)
delete from cte1
select * from #t
ii) If it is bulk insert then,you hv to do manipulation before bulk insert.
like if bulk insert count is greater than 100 then sort and keep last 100 rows and remove rest rows.
Related
I have a table of kicks between a number of football players. Most interactions have both a kicker and receiver, but sometimes the pass is made but never received. The table contains 3 columns. For purposes of the example, I have added a "PassID" column to assist with the description of the problem.
The table looks as follows:
create table #T (Player1 varchar(25),Action varchar(25),Player2 varchar(25),PassID int)
insert into #T select 'Jamie','Kicked to','Pierre',1
insert into #T select 'Pierre','Received from ','Jamie',1
insert into #T select 'Jamie','Kicked to ','Mohamed',2
insert into #T select 'Jamie','Received from ','Kun',3
insert into #T select 'Kun ','Kicked to','Jamie',3
insert into #T select 'Mohamed','Received from ','Pierre',4
insert into #T select 'Pierre','Kicked to','Mohamed',4
insert into #T select 'Mohamed','Kicked to','Kun',5
insert into #T select 'Jamie ','Kicked to ','Kun',6
insert into #T select 'Kun ','Received from ','Jamie',6
insert into #T select 'Jamie','Received from ','Kun',7
insert into #T select 'Kun ','Kicked to','Jamie',7
I have to answer the following question using SQL server:
How many unique interactions exist, where a unique interaction is defined as a kick between two players, whether completed or not and where the direction of the interaction does not matter?
In this simple example, I know the answer is 5,being:
Jamie/Pierre
Jamie/Mohamed
Jamie/Kun
Mohamed/Pierre
Mohamed/Kun
How do I extract this answer from the table using T-SQL statement?
SELECT COUNT(DISTINCT CASE
WHEN Player1 > Player2 THEN CONCAT(Player1,'+',Player2)
ELSE CONCAT(Player2,'+',Player1)
END )
FROM #T
WHERE Action = 'Kicked To';
Here is a SQL Fiddle
Try with the below code.
Select CONCAT(x.Player1,'/',x.Player2)Title from (
Select *,ROW_NUMBER() over (PARTITION by passid order by passid)Row from #T
)X
where Row=1
I am not sure in human language what this query will eventually do in SQL Server.
The idea is that if an order with the amount X exist in both tables #Temp and #TempDuplPos it should be deleted from the table #Temp.
DELETE #Temp
FROM #Temp
INNER JOIN #TempDuplPos ON (#Temp.[OrderNumber] = #TempDuplPos.[OrderNumber])
AND (#Temp.[Amount] = #TempDuplPos.[Amount])
What I did to test is the following:
SELECT 1 AS OrderNumber, 10 AS Amount
INTO #Temp
SELECT 1 AS OrderNumber, 10 AS Amount
INTO #TempDuplPos
INSERT INTO #Temp
VALUES (2,20)
INSERT INTO #TempDuplPos
VALUES (3,30)
DELETE #Temp
FROM #Temp
INNER JOIN #TempDuplPosON (#Temp.[OrderNumber] = #TempDuplPos.[OrderNumber])
AND (#Temp.[Amount] = #TempDuplPos.[Amount])
SELECT *
FROM #Temp
SELECT *
FROM #TempDuplPos
DROP TABLE #Temp
DROP TABLE #TempDuplPos
It looks like it does the job but I am not sure I miss something which will hit me in a large data set. So my question is, is this query doing what I want? If no what it does? Thanks!
It deletes records from #Temp table where records on #TempDuplPos with the same OrderNumber and Amount exists.
If you want to only delete records with a specific amount you need to add a where clause:
DELETE #Temp
FROM #Temp
INNER JOIN #TempDuplPos
ON (#Temp.[OrderNumber] = #TempDuplPos.[OrderNumber])
AND (#Temp.[Amount] = #TempDuplPos.[Amount])
WHERE #Temp.[Amount] = #Amount
I want to delete from an existing table the entries that respond to a specific time range if they exist in this table, then calculate them and insert them to it.
If they do not exist create them and just insert to the table.
How is that possible to be done?
Could anyone give an example of this?
The table structure should be the following:
create table test_table
(
[Date] float
,[UserName] nvarchar(max)
,[SessionType] int
,[Duration] float
,[MessageCount] int
)
if you have a Column that Stores the DATE and TIME then you can just delete the records based on that.
Suppose I have a Column Called CreateDate on My table. Then I can Delete all records Created between 10.00 am and 11.00 Today by Just Giving
DELETE FROM MyTable WHERE
CreateDate BETWEEN '2018-01-12 10:00:00.000' AND '2018-01-12 11:00:00.000'
Now Insert the values again using the Normal INSERT statement
You can do in steps like this
First store the set of records in time range in a temp table
SELECT * INTO tempTable FROM YourTable WHERE CONVERT(FLOAT, [Date]) BETWEEN 43100.3603763503 AND 43110.3603763503
Then delete the records from the table
DELETE FROM YourTable WHERE CONVERT(FLOAT, [Date]) BETWEEN 43100.3603763503 AND 43110.3603763503
Then do the calculations as per your requirement with the data available in tempTable and insert the data into your table
INSERT INTO YourTable
SELECT * FROM tempTable
Then drop the tempTable
DROP TABLE tempTable
I am updating my solution to this thank you all for help.
create mytable table
(
[Date] float
,[UserName] nvarchar(max)
,[SessionType] int
,[Duration] float
,[MessageCount] int
)
IF EXISTS (SELECT * FROM mytable WHERE [Date] >= 43082 AND [Date] < 43111)
BEGIN
DELETE FROM mytable WHERE [Date] >= 43082 AND [Date]< 43111
;WITH Data AS (
/*do the calculation of data*/
)
INSERT INTO mytable select * from Data
END
ELSE
BEGIN
;WITH Data AS (
/*do the calculation of data*/
)
INSERT INTO mytable select * from Data
END
I have an one table as below a picture which indicates some duplicated rows.I can find the duplicated rows but I could not able to delete it because of there is no any unique ID that I can distinguish. There were lots of duplicated rows like that in same table I just screenshot a piece of that.
As a result,according to the below picture, how can I delete the duplicated rows but keep original ?
One solution you could consider is copying all unique records into a temporary table, thus removing the duplicates. You could then truncate the original table and re-populate it from the temporary table you've created. The code would be something like this:
SELECT DISTINCT * INTO #tempTable FROM MyTable
TRUNCATE TABLE MyTable;
INSERT INTO MyTable (LocationID, UnitID, CameraID ... IsActiveHours)
SELECT LocationID, UnitID, CameraID ... IsActiveHours FROM #tempTable;
This isn't always an option due to key constraints and amount of data, but useful in certain cases. Take it as you may.
You could use a cte and Row_Number() to accomplish this. If you are satisfied with the results, remove the final select and un-comment the delete statement
;with cte as (
Select *,RowNr=Row_Number() over (Partition By LocationId Order by Date_T)
From YourTable
)
Select * from cte Where RowNr>1
-- Delete From cte Where RowNr>1
You would be best adding an identity column to make things easier however this can be done without a TRUNCATE using the following:
--GET DUPLICATE ROWS INTO A TEMP TABLE (YOU MAY NOT NEED TO USE ALL THE COLUMNS TO IDENTIFY A DUPLICATE)
SELECT ROW_NUMBER() OVER (ORDER BY ColA) AS RowNo, ColA, ColB, ColC, COUNT(*) As [Count]
INTO #TEMP1
FROM test
GROUP BY ColA, ColB, ColC
HAVING COUNT(*) > 1
--LOOP THROUGH DUPLICATES
DECLARE #RowNo INT
DECLARE #Duplicates INT
SET #RowNo = 1
WHILE EXISTS(SELECT * FROM #TEMP1)
BEGIN
--GET A COUNT OF ADDITIONAL ROWS FOR THIS DUPLICATE
SET #Duplicates = (SELECT [Count] FROM #TEMP1 WHERE RowNo = #RowNo) - 1
--DELETE THE ROWS WE DONT NEED
DELETE TOP (#Duplicates) t1
FROM test t1
JOIN #TEMP1 t2 ON t1.ColA = t2.ColA AND t1.ColB = t2.ColB AND t1.ColC = t2.ColC
WHERE t2.RowNo = #RowNo
--REMOVE THE ROW FROM THE TEMP TABLE
DELETE FROM #TEMP1 WHERE RowNo = #RowNo
--INCREASE THE ROW NO TO MOVE TO THE NEXT ROW
SET #RowNo = #RowNo + 1
END
--DROP THE TEMP TABLE
DROP TABLE #TEMP1
This is the query that fix this issue.
WITH X AS (
SELECT ROW_NUMBER() OVER(PARTITION BY LocationId,date_t ORDER BY LocationId desc) as 'rownum',LocationId,
date_T AS T
FROM Counts
)
--SELECT * FROM X WHERE rownum >1
DELETE FROM X
WHERE rownum <> 1
Is there a way to increment an ID field that has a primary key in an INSERT INTO SELECT statement?
What I would want to do is take the last ID of the table and insert an incremented ID with each new record produced by the INSERT INTO SELECT statement?
You can do it like this:
DECLARE #lastId int = 0
SELECT #lastId = MAX(Id) From YourTable
INSERT INTO YourTable (Id, Data)
SELECT (ROW_NUMBER() OVER (ORDER BY (SELECT 0))) + #lastId, at.Data
FROM AnotherTable at
Be sure to add it inside a Transaction scope.
SqlFiddle: http://www.sqlfiddle.com/#!3/d23642/5
Anyway I strongly suggest you to use an IDENTITY column to avoid collisions.
Maybe get the max id and then increse in one on each Insert
INSERT MAX(ID)+1
I think something like this is what you are looking for. Let's assume the PK is an INT for demo purposes.
--Get the last/greatest PK value in first table.
DECLARE #LastPKValue INT
SELECT #LastPKValue = MAX(PKCol)
FROM [schema].[YourTable]
INSERT INTO [schema].[YourTable] (PKCol, ColA, ColB, ColC)
SELECT
ROW_NUMBER() OVER( ORDER BY sot.[SomeColumnName]) + #LastPKValue,
OtherColumnA,
OtherColumnB,
OtherColumnC
FROM [schema].[SomeOtherTable] sot