【问题标题】:How to use SELECT in sqlcommand如何在 sqlcommand 中使用 SELECT
【发布时间】:2015-08-19 16:37:21
【问题描述】:

我有两张桌子

餐桌付款:

 paymentid   orderid{FK_payment_orderlist}    totalprice   datetime   status  RefID   SaleReferenceId

表格顺序表:

orderid    customerid   classid

我有一个这样的存储过程:

USE [miztahrirtest2]
GO
/****** Object:  StoredProcedure [dbo].[InsertPayment]    Script Date: 8/19/2015 8:51:08 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE  [dbo].[InsertPayment] @orderid int,@totalprice int,@status nvarchar(50),@new_identity    INT    OUTPUT
AS
BEGIN

    insert into payment(orderid,totalprice,[datetime],[status],RefID,SaleReferenceId) SELECT MAX(orderid) FROM orderlist As orderid,values(@orderid,@totalprice,GETDATE(),@status,'','')
    SELECT @new_identity = SCOPE_IDENTITY()
    SELECT @new_identity AS id
    return @new_identity
END

我想从orderlist 表中选择最后一个orderid 并在payment 表中设置另一个值,但该代码无法正常工作。我现在该怎么办?

【问题讨论】:

标签: asp.net sql-server stored-procedures


【解决方案1】:

您需要将 orderid 字段定义为identity,因此它将被自动处理,您应该将其从插入语句中删除。然后就可以使用scope_identity()来获取你插入的行得到的id值了。

所以插入语句应该是这样的:

insert into payment(totalprice,[datetime],[status],RefID,SaleReferenceId) 
values(@totalprice,GETDATE(),@status,'','')

【讨论】:

  • 我不建议对任何内容使用空字符串 (''),如果缺少值使用 NULL,如果是 ID,也许应该是数字?
  • 谢谢你,但我不知道如何定义它以及如何使用 scope_identity() 。你能用代码告诉我吗?
  • @mahdi.gh 插入后的scope_identity选择没问题,只需要identity字段,你必须在create table-clause中定义identity,或者使用alter table删除+添加列
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-30
  • 1970-01-01
相关资源
最近更新 更多