我试图用谷歌搜索它,但没有找到方法
我有一个 t-sql 脚本,它向表中添加一个新列,然后根据同一个表中的一些其他列用值填充该列,最后删除一些列。这一切正常。
当我想再次运行脚本时出现问题。我有一个 if 子句来检查缺失的列是否存在,但是即使 if 子句中的代码没有运行,SSMS 仍然会提示并显示错误消息。该脚本必须能够多次运行,而且我不希望显示错误消息!
在代码中(显然是测试代码,不想在此处转储生产代码......):
create table test (
Name text,
Switch int,
ValueA int,
ValueB int)
go
insert into test values ('Name', 0, 5, 10)
if not exists (select 1 from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'ValueC' and TABLE_NAME = 'test')
begin
alter table test
add ValueC int
end
go
-- This batch rasies error when run more then once!
if exists (select 1 from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'ValueA' and TABLE_NAME = 'test')
begin
update test
set ValueC = (select case Switch
when 0 then (select (ValueA - ValueB))
when 1 then (select (ValueB - ValueA))
end)
end
go
if exists (select 1 from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'ValueA' and TABLE_NAME = 'test')
begin
alter table test drop column ValueA
end
go
select * from test
--Name 0 10 -5
这是错误消息:
Msg 207, Level 16, State 1, Line 6
Invalid column name 'ValueA'.
Msg 207, Level 16, State 1, Line 7
Invalid column name 'ValueA'.
干杯
--乔克
最佳答案
是的,没有动态 SQL 是可能的,但有一些笨拙的解决方法。我只会用 EXEC
为了这。
SQL 2000 中的行为 is explained here
Erland Sommarskog 提到“一旦查询中的所有表都存在,SQL Server 就会对查询执行全面检查”。
因此,通过在查询中向不存在的表添加 no-op 引用,可以推迟编译。通过这种调整,下面的脚本可以多次运行而不会出现错误。
insert into test values ('Name', 0, 5, 10)
if not exists (select 1 from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'ValueC' and TABLE_NAME = 'test')
begin
alter table test
add ValueC int
end
go
create table #dummy
(i int)
-- This batch raised error when run more then once!
if exists (select 1 from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'ValueA' and TABLE_NAME = 'test')
begin
update test
set ValueC = (select case Switch
when 0 then (select (ValueA - ValueB))
when 1 then (select (ValueB - ValueA))
end) where not exists(select * from #dummy)
end
drop table #dummy
go
if exists (select 1 from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'ValueA' and TABLE_NAME = 'test')
begin
alter table test drop column ValueA
end
go
select * from test
--Name 0 10 -5
关于sql - 是否可以告诉 SSMS 不检查 t-sql 脚本中是否存在列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3290786/