SQL Server表名作为变量

时间:2019-01-21 13:56:24

标签: sql asp.net sql-server database

我正在使用sql server数据库创建一个Web应用程序。 我需要根据用户输入为每个用户为购物车动态创建表。 我成功创建了表,但是当我需要检查表中是否存在所选项目时,我遇到了一个问题, 您能请任何人帮我解决这个问题吗?

其他信息:

我有两个表dbo.Book是在之前创建的 和dbo.@TABLENAME通过IDBook连接到dbo.Book。

这是我尝试的代码。

    alter PROC insert_items

    @TABLENAME NVARCHAR(100),
    @IDBOOK NVARCHAR(6),
    @QUANTITY NVARCHAR(3)

    AS

    DECLARE @SQL NVARCHAR(MAX)

    IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @TABLENAME)
        BEGIN
            IF EXISTS (SELECT InStock, IDBook FROM Book WHERE InStock > 0
AND IDBook = @IDBOOK    AND InStock >= @QUANTITY)
                BEGIN
                    SET @SQL = 'CREATE TABLE ' + @TABLENAME + '(
                                id INT NOT NULL IDENTITY PRIMARY KEY,
                                IDBook INT  NOT NULL,
                                Quantity INT NOT NULL,
                                CONSTRAINT [FK_'+ @TABLENAME +'_Book] FOREIGN KEY([IDBook])
                                REFERENCES [dbo].[Book] ([IDBook])
                                ON UPDATE CASCADE 
                                ON DELETE CASCADE )
                                INSERT INTO ' + @TABLENAME + ' 
                                VALUES ('''+@IDBOOK +''','''+ @QUANTITY + ''')'
                    EXEC sp_executesql  @SQL
                    UPDATE Book SET InStock = InStock - @QUANTITY WHERE IDBook = @IDBOOK
                    RETURN 0
                END
            ELSE
                BEGIN
                    RETURN 1
                END
        END
    ELSE
        BEGIN
            IF NOT EXISTS (SELECT IDBook FROM @TABLENAME WHERE IDBook = @IDBOOK )
                BEGIN
                    SET @SQL = 'INSERT INTO ' + @TABLENAME + ' 
                                VALUES ('''+@IDBOOK +''','''+ @QUANTITY + ''')'
                    EXEC sp_executesql  @SQL
                    UPDATE Book SET InStock = InStock - @QUANTITY WHERE IDBook = @IDBOOK
                    RETURN 0
                END
        END
  

消息1087,级别16,状态1,过程insert_items,第36行[批处理   起始行0]必须声明表变量“ @TABLENAME”。

这些行有错误

IF NOT EXISTS (SELECT IDBook FROM @TABLENAME WHERE IDBook = @IDBOOK )

1 个答案:

答案 0 :(得分:0)

// Images are the ones that need to change visibility
let images = document.querySelectorAll('.backSide');

// Cards are the ones that need to be clicked
let cards = document.querySelectorAll('.card');

images.forEach(cardImage => cardImage.classList.add('flip'));
cards.forEach(card => card.addEventListener('click', showCard));

function showCard() {
    // This can be done with toggle of the class as per another answer
    this.classList.remove('flip');
    this.style.visibility = 'visible';
}

尝试上面的代码...虽然不能想到您需要动态创建此表的原因!