这是一个具有约束力的问题。代码在编译时绑定到表的元数据,并且没有后期绑定。尝试使用EXEC和动态SQL克服此限制:
BEGIN TRANSACTION;
PRINT 'Adding column, ''SupplementalDividends'', to MyTable table.';
ALTER TABLE MyTable
ADD SupplementalDividends DECIMAL(18,6);
PRINT 'Column added successfully....';
PRINT 'Ready to INSERT into MyTable ...';
EXEC('
INSERT INTO MyTable (x, SupplementalDividends)
VALUES (1, 3.2);
')
PRINT '**** CHANGES COMPLETE -- COMMITTING.';
COMMIT TRANSACTION;
另一种选择是使用存储过程插入数据:后期绑定适用于存储过程,但不适用于临时查询。同样,您将不得不使用动态SQL创建过程,但是它可以使您更轻松地传递参数:
BEGIN TRANSACTION;
PRINT 'Adding column, ''SupplementalDividends'', to MyTable table.';
ALTER TABLE MyTable
ADD SupplementalDividends DECIMAL(18,6);
PRINT 'Column added successfully....';
PRINT 'Ready to INSERT into MyTable ...';
EXEC('
CREATE PROCEDURE insData @p1 int, @p2 DECIMAL(18,6)
AS
BEGIN
INSERT INTO MyTable (x, SupplementalDividends)
VALUES (@p1, @p2);
END')
EXEC InsData 1, 3.2;
PRINT '**** CHANGES COMPLETE -- COMMITTING.';
COMMIT TRANSACTION;
临时存储过程也可以工作:
BEGIN TRANSACTION;
PRINT 'Adding column, ''SupplementalDividends'', to MyTable table.';
ALTER TABLE MyTable
ADD SupplementalDividends DECIMAL(18,6);
PRINT 'Column added successfully....';
PRINT 'Ready to INSERT into MyTable ...';
EXEC('
CREATE PROCEDURE #insData @p1 int, @p2 DECIMAL(18,6)
AS
BEGIN
INSERT INTO MyTable (x, SupplementalDividends)
VALUES (@p1, @p2);
END')
EXEC #InsData 1, 3.2;
PRINT '**** CHANGES COMPLETE -- COMMITTING.';
COMMIT TRANSACTION;
schema.ObjectName
。适应良好做法的一个好的开始:-)