MS SQL Server写动态SQL时,比如动态创建表,修改表,添加字段,我们需要判断字段是否存在。
你可以参考下面自定义函数:
源代码:
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 FUNCTION [dbo].[usp_IsExistsColumn] ( @TABLE_CATALOG SYSNAME, @TABLE_SCHEMA SYSNAME, @TABLE_NAME SYSNAME, @COLUMN_NAME SYSNAME ) RETURNS BIT BEGIN DECLARE @isExists BIT = 0 IF EXISTS(SELECT TOP 1 1 FROM [tempdb].[sys].[columns] WHERE object_id = object_id(@TABLE_CATALOG + N'.'+ @TABLE_SCHEMA + N'.' + @TABLE_NAME) AND [name] = @COLUMN_NAME) OR EXISTS(SELECT TOP 1 1 FROM [sys].[columns] WHERE object_id = object_id(@TABLE_CATALOG + N'.'+ @TABLE_SCHEMA + N'.' + @TABLE_NAME) AND [name] = @COLUMN_NAME) SET @isExists = 1 RETURN @isExists END GO