将数据插入表并从增加的主键获取ID

时间:2020-02-16 18:01:36

标签: c# asp.net sql-server tsql

在ASP.NET应用程序中,我需要执行以下操作:首先,从用户获取数据,其次将数据插入SQL Server数据库表,然后从该表获取ID值( (它会自动递增),然后在另一个表的另一个插入中使用它。

现在,我已经发现要执行此操作,我需要使用T-SQL OUTPUT子句。但是,当我尝试执行此操作时,出现此错误:

enter image description here

我尝试遵循这些帖子中的建议: Get output parameter value in ADO.NETUse SQL Server Stored procedure output in asp.net c# 但我无法使其正常工作。

我没有使用存储过程,而是使用了一条SQL语句。在这里:

INSERT INTO BS_product_sets (User_id, Set_name, Set_id, Products_count) 
OUTPUT inserted.ID INTO @NEWID 
VALUES (@UID, @SNAME, @SPREFIX, @PCOUNT)

我也尝试过:

DECLARE @NEWID int; 

INSERT INTO BS_product_sets (User_id, Set_name, Set_id, Products_count) 
OUTPUT inserted.ID INTO @NEWID 
VALUES (@UID, @SNAME, @SPREFIX, @PCOUNT)

但是后来变得更奇怪了,因为我得到的错误是:

enter image description here

你们中有人知道如何解决吗?这是我在C#中剩下的代码:

public void InsertProductAutoBinds(int user_id, int parameters_count, List<int> cat_ids, List<string> names, List<string> values, string set_name, string set_id)
{
    SqlConnection connection = new SqlConnection(DatabaseConstants.ConnectionString);

    // Adding set to database
    SqlCommand command = new SqlCommand(DatabaseConstants.InsertSet, connection);
    command.Parameters.AddWithValue("@UID", user_id);
    command.Parameters.AddWithValue("@SNAME", set_name);
    command.Parameters.AddWithValue("@SPREFIX", set_id);
    command.Parameters.AddWithValue("@PCOUNT", 0);
    command.Parameters.Add("@NEWID", SqlDbType.Int).Direction = ParameterDirection.Output;

    connection.Open();
    command.ExecuteNonQuery();

    int new_inserted_id = Convert.ToInt32(command.Parameters["@NEWID"].Value);

    connection.Close();

    // Adding binds
    command = new SqlCommand(DatabaseConstants.InsertAutoBinds1, connection);
    command.Parameters.AddWithValue("@UID", user_id);
    command.Parameters.AddWithValue("@SID", new_inserted_id);
    command.Parameters.AddWithValue("@P1ID", cat_ids[0]);
    command.Parameters.AddWithValue("@VN1", names[0]);
    command.Parameters.AddWithValue("@VS1", values[0]);

    if (parameters_count > 1)
    {
        command.CommandText = DatabaseConstants.InsertAutoBinds2;
        command.Parameters.AddWithValue("@P2ID", cat_ids[1]);
        command.Parameters.AddWithValue("@VN2", names[1]);
        command.Parameters.AddWithValue("@VS2", values[1]);
    }

    if (parameters_count > 2)
    {
        command.CommandText = DatabaseConstants.InsertAutoBinds3;
        command.Parameters.AddWithValue("@P3ID", cat_ids[2]);
        command.Parameters.AddWithValue("@VN3", names[2]);
        command.Parameters.AddWithValue("@VS3", values[2]);
    }

    connection.Open();
    command.ExecuteNonQuery();
    connection.Close();
}

2 个答案:

答案 0 :(得分:3)

如果您查看official MS documentation for INSERT INTO,将会看到:

OUTPUT INTO {@table_variable | output_table}

这意味着:$post['apiKey'] = $apiKey; $ch = curl_init(); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_URL,"https://www.pawnhost.com/phevapi/verify_api.php"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $res = curl_exec($ch); if ($res === FALSE) { echo "Curl Error:" . curl_error($ch); } curl_close($ch); print_r($res); 子句仅在以表或表变量为目标的情况下起作用-您不能执行<?php define("ERROR_HEADER_URL", "Location: " . $_SERVER['HTTP_REFERER'] . "?error="); require("includes/initialize.php"); if ($_SERVER['REQUEST_METHOD'] != 'POST') header(ERROR_HEADER_URL . "invalidRequest"); if (!isset($_POST['apiKey'])) header(ERROR_HEADER_URL . "verficationFailed"); $apiKey = escape($_POST['apiKey']); if (isInputEmpty($apiKey)) { header(ERROR_HEADER_URL . "emptyFields"); } elseif (!$apiKey == 25) { header(ERROR_HEADER_URL . urlencode("invalidKey")); } else { $response = []; if (getApiKeyUserDetails($apiKey, $connection)) { if (getApiKeyUserDetails($apiKey, $connection)['apiKeyUsed'] > 0) { $response['success'] = false; $response['error'] = 'apiKeyUsed'; } else { makeApiKeyUsed($apiKey, $connection); $response['success'] = true; } } else { $response['success'] = false; $response['error'] = 'invalidApiKey'; } return json_encode($response); } -只是不支持。

所以您需要

  • 执行OUTPUT ... INTO ....,然后从该表变量中选择第一个值并返回它
  • 只需使用OUTPUT .... INTO @variable而没有任何OUTPUT ... INTO @tableVar),只需获取C#代码中SQL命令返回的值即可-在这种情况下,由于数据已返回,则需要在C#代码中使用OUTPUT inserted.ID而不是INTO ....

答案 1 :(得分:0)

如果有:

CREATE TABLE tab (Id Int IDENTITY, User_Id Int, ...)

DECLARE @NewID Int

INSERT INTO tab (User_Id,...) VALUES (123, ...)

SET @NewId = @@Identity