通过存储过程在运行时创建 table 在 SQL 服务器上成功执行,但应用程序执行时出现运行时错误

Creating a table at run time by stored procedure is executed on SQL Server successfully but run time error on application execution

SQL Server 存储过程:

ALTER PROCEDURE [dbo].[tblfrends] 
    @TABLENAME nvarchar
AS
BEGIN-- use body wrappers around whole body
  SET NOCOUNT ON; -- put this at the beginning - no point in setting it at the end

  DECLARE @SQL NVARCHAR(MAX); -- dynamic SQL should always be Unicode

  SELECT @SQL = 'CREATE TABLE' + QUOTENAME(@TABLENAME) + '(`friend_one` INT,
                                                                `friend_two` INT,
                                                                `status` nvarchar(10) ,
                                                   PRIMARY KEY (`friend_one`,`friend_two`);'

  EXEC sp_executesql @sql; -- instead of EXEC(@sql)
END

C#代码:

public void createtable()
{
    SqlCommand sqlCommand = new SqlCommand("tblfrends", access.sqlConnection);
    sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;

    sqlCommand.Parameters.Add("@TABLENAME",System.Data.SqlDbType.NVarChar);
    sqlCommand.Parameters["@TABLENAME"].Value = Name.Text;

    access.crud(sqlCommand);

    if (sqlCommand.UpdatedRowSource > 0)
    {
        Response.Write("frend table");
    }
    else
    {
        Response.Write("tayn tayn fishhh");
    }
}

运行时错误:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

Additional information: Incorrect syntax near '`'.

这就是你的@SQL变量变成的:

CREATE TABLE[s](`friend_one` INT,
       `friend_two` INT,
        `status` nvarchar(10) ,
        PRIMARY KEY (`friend_one`,`friend_two`);

如您所见,存在多个问题。错误的单引号和缺少括号。您还试图添加多个主键。

尝试像这样更改您的存储过程:

SELECT @SQL = 'CREATE TABLE' + QUOTENAME(@TABLENAME) + '(friend_one INT PRIMARY KEY,
       friend_two INT,
       status nvarchar(10))'

所以你的@SQL变量会变成这样:

CREATE TABLE[s](friend_one INT PRIMARY KEY,
                friend_two INT,
                status nvarchar(10))

没有你存储过程的语法错误。

这应该是正确的文字

ALTER PROCEDURE [dbo].[tblfrends] 
                @TABLENAME nvarchar(255) 
AS 
BEGIN

    DECLARE @SQL NVARCHAR(MAX)
    SELECT @SQL = N'CREATE TABLE ' + QUOTENAME(@TABLENAME) + 
                  N' (friend_one INT, friend_two INT, status nvarchar(10),' + 
                  N' PRIMARY KEY (friend_one,friend_two))'
    EXEC sp_executesql @sql

END

首先 你需要指定sp接收到的参数@TableName的大小,否则它被假定为一个字符长,你得到一个table名称只有第一个字母。

第二个 您在 PRIMARY KEY 声明后错过了右括号。

最后,导致失败并不是真正的问题,但是...,在 QUOTENAME 命令前后添加空格,并注意 SQL 服务器不希望在字段名称周围使用反引号。