判断列名是否存在
程序员文章站
2022-05-28 15:51:16
实现动态化,为表添加存储时间字段,Insus.NET写一个存储过程,如下 SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- -- Author: Insus.NET -- Blog: https://insus.cnblogs.com -- Cr ......
实现动态化,为表添加存储时间字段,insus.net写一个存储过程,如下
set ansi_nulls on go set quoted_identifier on go -- ============================================= -- author: insus.net -- blog: https://insus.cnblogs.com -- create date: 2019-05-29 -- update date: 2019-05-29 -- description: 动态为表添加存储时间字段 -- ============================================= create procedure [dbo].[usp_dyanmicallyaddstoragedatetimefield] ( @table_catalog sysname, @table_schema sysname, @table_name sysname, @columns nvarchar(max) -- '[column1],[column2],[column3]...' ) as begin declare @source table ([id] int identity(1,1), [value] nvarchar(max)) insert into @source ([value]) select [value] from [dbo].[tvf_convertstringtotable](@columns,',') declare @r int = 1,@rs int = 0 select @rs = max([id]) from @source while @r <= @rs begin declare @column_name sysname select @column_name = convert(varchar(30), [value], 23) from @source where [id] = @r execute('if [dbo].[usp_isexistscolumn]('''+ @table_catalog +''','''+ @table_schema +''','''+ @table_name +''','''+ @column_name +''') = 0 alter table '+ @table_name +' add '+ @column_name +' datetime') set @r= @r + 1 end end
上面存储过程代码#54行中有一个定义函数:[dbo].[tvf_convertstringtotable]()
是分割字符串转为表。函数详细代码参考这篇《展开中断或忽略的序号》
还有一个自定义函数:[dbo].[usp_isexistscolumn]()这是判断表的列是否存在。
参考:《判断列名是否存在》
接下来,insus.net演示这个存储过程[dbo].[usp_dyanmicallyaddstoragedatetimefield]:
if object_id('tempdb..#temprpt') is not null drop table #temprpt create table #temprpt ( [caseno] bigint, [username] nvarchar(20) ) execute [dbo].[usp_dyanmicallyaddstoragedatetimefield] 'tempdb','dbo','#temprpt','[column1],[column2],[column3]' select * from #temprpt
上一篇: Jquery取得iframe下内容的方法
推荐阅读
-
sql server判断数据库、表、列、视图是否存在
-
js如何判断复选框是否被选中(js获取复选框选中的值)
-
C#判断程序是否是管理员权限运行的方法代码示例
-
判断多个元素(RADIO,CHECKBOX等)是否被选择的原理说明
-
Javascript select控件操作大全(新增、修改、删除、选中、清空、判断存在等)
-
自写简单JS判断是否已经弹出页面
-
Python判断列表是否已排序的各种方法及其性能分析
-
jquery判断字符串是否为空(jquery设置input的value值)
-
android判断phonegap是否联网且加载super.loadUrl网址
-
Android编程判断SD卡是否存在及使用容量查询实现方法