日期:2014-05-18 浏览次数:20464 次
using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; /// <summary> /// 引用请保留以下信息: /// /// 用户自定CLR函数,用来生成一个序列 /// by:jinjazz(近身剪) /// http://blog.csdn.net/jinjazz /// /// </summary> public partial class UserDefinedFunctions { /// <summary> /// 初始化查询标识 /// </summary> public static System.Collections.Generic.Dictionary<string, long> rnList = new System.Collections.Generic.Dictionary<string, long>(); /// <summary> /// 根据标识获取序列 /// </summary> /// <param name="key">查询标识</param> /// <returns></returns> [Microsoft.SqlServer.Server.SqlFunction] public static SqlInt64 GetRowNum(SqlString key) { try { if (rnList == null) rnList = new System.Collections.Generic.Dictionary<string, long>(); if (rnList.ContainsKey(key.Value) == false) rnList.Add(key.Value, 1); return rnList[key.Value]++; } catch { return -1; } } /// <summary> /// 销毁查询标识 /// </summary> /// <param name="key"></param> [Microsoft.SqlServer.Server.SqlProcedure] public static void GetRowNumEnd(SqlString key) { try { if (rnList == null || rnList.ContainsKey(key.Value) == false) return ; rnList.Remove(key.Value); return ; } catch { } } };
exec sp_configure 'show advanced options', '1'; go reconfigure; go exec sp_configure 'clr enabled', '1' go reconfigure; exec sp_configure 'show advanced options', '1'; go --测试数据库 create database testDB go use testDB go ALTER DATABASE testDB SET TRUSTWORTHY On go CREATE ASSEMBLY testAss FROM 'E:\SqlServerProject3.dll' WITH PERMISSION_SET = UnSAFE; -- go CREATE FUNCTION dbo.GetRowNum ( @key nvarchar(100) ) RETURNS bigint AS EXTERNAL NAME testAss.[UserDefinedFunctions].GetRowNum go CREATE proc dbo.GetRowNumEnd ( @key nvarchar(100) ) AS EXTERNAL NAME testAss.[UserDefinedFunctions].GetRowNumEnd
--获取带行号的结果 select *,rn=dbo.GetRowNum(1) from sysobjects --清理结果 exec GetRowNumEnd 1
select count(*) from syscolumns a,syscolumns b,syscolumns c --75151448
declare @key varchar(100) set @key=newid() select top 10 * from( select a.* ,dbo.GetRowNum(@key