本文主要是介绍SQL[游标+动态SQL+表函数]返回指定表名的某行的所有列合并后的值,主要提供给数据库表的更新记录事件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Create PROCEDURE [dbo].[SysGetTableFieldsCombine]
-- =============================================
-- Description: <返回指定表名的某行的所有列合并后的值,主要提供给数据库表的更新记录事件>
-- Return 0- 成功, -1- 没有这个表
-- Rev: 1.00
-- =============================================
@ObjectName Nvarchar(100) ='',
@ObjectPKId char(12)='',
@CombineFieldsValue nvarchar(max) ='' output
AS
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
--判断表名是否存在
if object_id(@ObjectName) is null
return -1
--定义一个内存表,用来获取该表的所有字段清单
declare @tempFields table(ObjectColumnName nvarchar(100),ObjectColumnType nvarchar(100))
insert into @tempFields
SELECT c.name AS ObjectColumnName,t.name AS ObjectColumnType
FROM sys.syscolumns AS c INNER JOIN
sys.systypes AS t ON c.xusertype = t.xusertype
WHERE (id = Object_Id(@ObjectName))
ORDER BY colorder
--定义游标,开始拼接一个SQL查询字串
declare @SQLString nvarchar(max)
declare @ObjectColumnName nvarchar(100)
declare @PKFieldName nvarchar(100)
declare @CombineField nvarchar(200)
declare @Paramstring nvarchar(100)
declare @ObjectColumnType nvarchar(100)
set @SQLString='select @CField='
set @PKFieldName=''
DECLARE My_cursor CURSOR FOR SELECT --定义一个游标
ObjectColumnName,ObjectColumnType FROM @tempFields
OPEN My_cursor
FETCH NEXT FROM My_cursor INTO
@ObjectColumnName,@ObjectColumnType
WHILE @@fetch_status = 0
begin
IF @@fetch_status = -2
CONTINUE
if @ObjectColumnType<>'varbinary' and @ObjectColumnType<>'uniqueidentifier'
and @ObjectColumnType<>'timestamp' and @ObjectColumnType<>'image'
and @ObjectColumnType<>'binary'
begin
set @CombineField=''
IF @ObjectColumnType <> 'datetime'
SET @CombineField=''' ['+@ObjectColumnName+']''+rtrim(convert(nvarchar,isnull(convert(nvarchar,' + @ObjectColumnName + '),'''')))'
ELSE
SET @CombineField=''' ['+@ObjectColumnName+']''+rtrim(convert(nvarchar,isnull(convert(nvarchar,' + @ObjectColumnName + ',121),'''')))'
if @PKFieldName=''
begin
set @SQLString=@SQLString+ @CombineField
end
else
begin
set @SQLString=@SQLString+ '+'+ @CombineField
end
if @PKFieldName='' --获取主PK字段的名称
set @PKFieldName=@ObjectColumnName
end
FETCH NEXT FROM My_cursor INTO
@ObjectColumnName,@ObjectColumnType
end
DEALLOCATE My_cursor
set @SQLString=@SQLString+' from '+ @ObjectName+ ' where ' + @PKFieldName + ' =''' + @ObjectPKId + ''''
set @Paramstring='@CField nvarchar(max) output'
--动态执行SQL,同时从内部返回变量
EXECUTE sp_executesql @SQLString,@Paramstring,@CField=@CombineFieldsValue output
return 0
这篇关于SQL[游标+动态SQL+表函数]返回指定表名的某行的所有列合并后的值,主要提供给数据库表的更新记录事件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!