SQL 服务器插入查询

SQL Server Insert query

这是我的问题的简化版本。我下面有 2 tables

ProductInformtaionType

ProductInformationTypeID  Name     isText  isInteger  isDecimal is Boolean
1                         barcode    1        0           0        0
2                         Vatable    0        0           0        1
3                         Quantity   0        1           0        0 

ProductInformtaion

ProductInformtaion  ProductID   ProductInformtaionTypeID  ValueText   ValueInteger ValueDecimal

当我得到一些值时,我需要一个插入查询,它将数据插入到相关字段中。例如,数量是整数,所以我需要将该产品插入产品信息 table 并且只填充 isIntegerfield

如何创建动态插入查询来填充正确的字段,而不是使用 where istext = 1 子句为 (istext、isInteger、isBoolean、isDecimal) 插入 4 个单独的插入

这行得通。创建一个接受所有参数的存储过程。然后,只需将 NULL 值传递给它。例如,要仅插入 'Column3',您可以调用:

Exec dbo.[Test_Stored_Procedure] @Column3 = 'hey!!!'

或者,您可以这样做:

Exec dbo.[Test_Stored_Procedure] @Column1 = null, @Column2 = null, @Column3 = 'hey!!!', @Column4 = null

存储过程代码如下:

CREATE PROCEDURE [dbo].[Test_Stored_Procedure]
    @Column1 varchar(50) = null,
    @Column2 varchar(50) = null,
    @Column3 varchar(50) = null,
    @Column4 varchar(50) = null
AS
BEGIN
    INSERT INTO YourTable
    VALUES
    (@Column1, @Column2, @Column3, @Column4)
END