我有一個很長的腳本,我希望能夠在需要時運行整個文件,而不必擔心它的部分是否已經運行。但是下面的腳本給我帶來了問題。由於某些原因,即使列'EntityID'和'EntityType'不存在,它也會越過IF語句,在這種情況下,它不應該通過IF語句。有人能告訴我什麼是錯的嗎?SQL IF語句被忽略
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Notes' AND COLUMN_NAME IN ('EntityId', 'EntityType'))
BEGIN
BEGIN TRANSACTION
--Delete notes where EntityType and EntityID are both NULL
DELETE FROM [dbo].[Notes]
WHERE [EntityId] = NULL
AND [EntityType] = NULL
--Delete notes where the corresponding contact or account has been deleted.
OR [ID] IN (9788, 10684, 10393, 10718, 10719)
--Populate new columns with all existing data
UPDATE [dbo].[Notes]
SET [AccountId] = [EntityId]
WHERE [EntityType] = 1
UPDATE [dbo].[Notes]
SET [ContactId] = [EntityId]
WHERE [EntityType] = 2
--Delete EntityId and EntityType columns from the Notes table
ALTER TABLE [dbo].[Notes]
DROP COLUMN [EntityId], [EntityType]
COMMIT
END
GO
的腳本表
CREATE TABLE [dbo].[Notes](
[ID] [int] IDENTITY(1,1) NOT NULL,
[AnnotationID] [uniqueidentifier] NULL,
[CreatedBy] [int] NULL,
[CreatedDate] [datetime] NULL,
[NoteText] [ntext] NULL,
[OriginalAnnotationID] [uniqueidentifier] NULL,
[Active] [bit] NULL,
[ContactId] [int] NULL,
[AccountId] [int] NULL,
CONSTRAINT [PK_Notes] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Notes] WITH CHECK ADD CONSTRAINT [FK_Account_ID] FOREIGN KEY([AccountId])
REFERENCES [dbo].[Account] ([ID])
GO
ALTER TABLE [dbo].[Notes] CHECK CONSTRAINT [FK_Account_ID]
GO
ALTER TABLE [dbo].[Notes] WITH CHECK ADD CONSTRAINT [FK_ContactId_ID] FOREIGN KEY([ContactId])
REFERENCES [dbo].[Contact] ([ID])
GO
ALTER TABLE [dbo].[Notes] CHECK CONSTRAINT [FK_ContactId_ID]
GO
的錯誤:
Msg 207, Level 16, State 1, Line 6
Invalid column name 'EntityId'.
Msg 207, Level 16, State 1, Line 7
Invalid column name 'EntityType'.
Msg 207, Level 16, State 1, Line 12
Invalid column name 'EntityType'.
Msg 207, Level 16, State 1, Line 16
Invalid column name 'EntityType'.
你確定這些列不存在嗎? - 嘗試在'IF'上面粘貼'select'語句,看看它返回什麼(如果有的話) –
只有當沒有列存在時才返回false。所以,如果其中一個... –
是否有可能有一個名爲'Notes'的表在不同的模式?你也應該指定'TABLE_SCHEMA'。或者更好的是,使用'sys.columns'(閱讀:http://sqlblog.com/blogs/aaron_bertrand/archive/2011/11/03/the-case-against-information-schema-views.aspx) –