Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 How to insert top 1 and top 3 on other table

Author  Topic 

programer
Posting Yak Master

221 Posts

Posted - 2013-09-15 : 07:03:17
Hi,

In the first table table1 I Inserted 3 rows.
Id, values
1, test1
2, test2
3, test3

in the second table2 I want to insert only row 1 and 3

I tried:
ALTER TRIGGER BetSlipEventsTrigger
ON dbo.tbl_BetSlipEvents
AFTER INSERT

AS

BEGIN

INSERT TOP (1) INTO tbl_BetSlipSystem ( BetSlipEventId )SELECT TOP 1 ID
FROM INSERTED

INSERT TOP (3) INTO tbl_BetSlipSystem ( BetSlipEventId )SELECT TOP 3 ID
FROM INSERTED


END

Not works. This code inserted 3 rows.

VeeranjaneyuluAnnapureddy
Posting Yak Master

169 Posts

Posted - 2013-09-16 : 00:38:33
INSERT INTO tbl_BetSlipSystem SELECT ID,BetSlipEventId
FROM INSERTED
WHERE ID in (1,3)

veeranjaneyulu
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2013-09-17 : 11:49:32
[code]ALTER TRIGGER dbo.BetSlipEventsTrigger
ON dbo.tbl_BetSlipEvents
AFTER INSERT,
UPDATE,
DELETE
AS

SET NOCOUNT ON;

WITH cteSource(ID, rn)
AS (
SELECT ID,
ROW_NUMBER() OVER (ORDER BY ID) AS rn
FROM dbo.tbl_BetSlipEvents
)
MERGE dbo.tbl_BetSlipSystem AS tgt
USING (
SELECT ID
FROM cteSource
WHERE rn IN (1, 3)
) AS src
WHEN NOT MATCHED BY TARGET
THEN INSERT (
BetSlipEventID
)
VALUES (
src.ID
)
WHEN NOT MATCHED BY SOURCE
THEN DELETE;[/code]


Microsoft SQL Server MVP, MCT, MCSE, MCSA, MCP, MCITP, MCTS, MCDBA
Go to Top of Page
   

- Advertisement -