我正在尝试在SQL中构建一个动态查询,它根据“字段选项”添加“语句”列,如表格Image所示。 (请参阅附表)
如果'Field Options'= A,则Field Name ='SINGLE PAY'。然后,这应该将'Statement'列填充为'SELECT SINGLE PAY FROM'...
如何使用游标迭代我表格的每一行并为我建立一个名为'Statement'的第三列?
enter codeDECLARE @field_option nvarchar(max) = 'B'
DECLARE @field_name nvarchar(max)
DECLARE @statement nvarchar(max)
IF @field_option = 'A'
BEGIN
SET @field_name = 'Single Pay'
SET @statement = 'SELECT '+ @field_name+'...'
SELECT @field_option AS 'Field_Option', @field_name AS 'Field_Name', @statement AS 'Statement'
INTO new_table
SELECT * FROM new_table;
END
ELSE IF @field_option = 'B'
BEGIN
SET @field_name = 'Double Pay'
SET @statement = 'SELECT '+ @field_name+'...'
SELECT @field_option AS 'Field_Option', @field_name AS 'Field_Name', @statement AS 'Statement'
INTO new_table
SELECT * FROM new_table;
END here
我面临的问题是,当我尝试第二次执行查询时,例如选项'B',我得到错误“数据库中已经有一个名为'new_table'的对象。”
如何在现有的“new_table”中添加新行?有人可以指导吗?
答案 0 :(得分:0)
这应该这样做:
DECLARE @field_option nvarchar(max) = 'B'
DECLARE @field_name nvarchar(max)
DECLARE @statement nvarchar(max)
IF OBJECT_ID('new_table') IS NOT NULL
DROP TABLE new_table
IF @field_option = 'A'
BEGIN
SET @field_name = 'Single Pay'
SET @statement = 'SELECT '+ @field_name+'...'
SELECT @field_option AS 'Field_Option', @field_name AS 'Field_Name', @statement AS 'Statement'
INTO new_table
SELECT * FROM new_table;
END
ELSE IF @field_option = 'B'
BEGIN
SET @field_name = 'Double Pay'
SET @statement = 'SELECT '+ @field_name+'...'
SELECT @field_option AS 'Field_Option', @field_name AS 'Field_Name', @statement AS 'Statement'
INTO new_table
SELECT * FROM new_table;
END
在你运行一次语句后(我猜测试时),表格已经完成。现在它就在那里,不会自行消失。因此,检查它是否存在于顶部并放下它。或者你可以考虑使用: