Showing posts with label SQL Code Library. Show all posts
Showing posts with label SQL Code Library. Show all posts

Retrieve Top n Records Per Group

Retrieve Top n Records Per Group

SELECT
DiscussionTopPosts.PostID
From (
SELECT p.DiscussionID, p.PostID, ROW_NUMBER() OVER (PARTITION BY p.DiscussionID ORDER BY p.DateCreated DESC) AS RowNumber
FROM Posts p
WHERE
p.DiscussionID IN
(
SELECT d.DiscussionID
FROM Discussions d
Where myCondition
)
AND p.IsActive = 1
GROUP BY p.DiscussionID, p.PostID, p.DateCreated
)
DiscussionTopPosts
WHERE
DiscussionTopPosts.RowNumber <= @NumberOfPosts

Generate INSERT Statements

Procedure to script your data (to generate INSERT statements from the existing data)


This procedure generates INSERT statements using existing data from the given tables and views. Later, you can use these INSERT statements to generate the data. It's very useful when you have to ship or package a database application. This procedure also comes in handy when you have to send sample data to your vendor or technical support provider for troubleshooting purposes.


Create Procedure [dbo].[InsertScriptGenerator]
/*
exec sp_CreateDataLoadScript 'MyTable'
*/

@TblName varchar(128)
as

create table #a (id int identity (1,1), ColType int, ColName varchar(128))

insert #a (ColType, ColName)
select case when DATA_TYPE like '%char%' then 1 else 0 end ,
COLUMN_NAME
from information_schema.columns
where TABLE_NAME = @TblName
order by ORDINAL_POSITION


if not exists (select * from #a)
begin
raiserror('No columns found for table %s', 16,-1, @TblName)
return
end

declare @id int ,
@maxid int ,
@cmd1 varchar(7000) ,
@cmd2 varchar(7000)

select @id = 0 ,
@maxid = max(id)
from #a

select @cmd1 = 'select '' insert ' + @TblName + ' ( '
select @cmd2 = ' + '' select '' + '
while @id < @maxid
begin
select @id = min(id) from #a where id > @id

select @cmd1 = @cmd1 + ColName + ','
from #a
where id = @id

select @cmd2 = @cmd2
+ ' case when ' + ColName + ' is null '
+ ' then ''null'' '
+ ' else '
+ case when ColType = 1 then ''''''''' + ' + ColName + ' + ''''''''' else 'convert(varchar(20),' + ColName + ')' end
+ ' end + '','' + '
from #a
where id = @id

end


select @cmd1 = left(@cmd1,len(@cmd1)-1) + ' ) '' '
select @cmd2 = left(@cmd2,len(@cmd2)-8) + ' from ' + @tblName
select '/*' + @cmd1 + @cmd2 + '*/'


exec (@cmd1 + @cmd2)
drop table #a