在同一个表中,必须添加一个列,它自动连接id(唯一+1)和名称 [英] in same table a column must be added which concatenates the id (unique +1) and name automaticly

查看:51
本文介绍了在同一个表中,必须添加一个列,它自动连接id(唯一+1)和名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

create table cust
(
id int identity(1,1),
cname varchar(20),
myid varchar(50)
)



--------------------------------------- -------------



i希望自动将其存储在myid栏中


----------------------------------------------------

i want to store this in myid column automatically

select cname+''+convert(varchar(50),id) as myid from cust where id=max(id)+1




id		cname		myid
-------------------------------------------------------
1		abc		abc1

推荐答案

创建插入触发器 [ ^ ]并将代码放在那里计算[myid]。



有关详细信息,请参阅这些CP文章

触发器 - SQL Server [ ^ ]

Be编写SQL触发器时​​非常小心 [ ^ ]

SQL:定位触发器 [ ^ ]
Create a "for insert" trigger[^] on the table and place your code to "calculate" [myid] in there.

See these CP articles for more information
Triggers -- SQL Server[^]
Be Very Careful When You Write SQL Trigger[^]
SQL:Target a Trigger[^]


我是建议你使用存储过程。



I'd suggest you to use stored procedure.

CREATE PROCEDURE uspNewCustomer
    @custname NVARCHAR(50)
BEGIN
    DECLARE @myid INT = 0 --in case of error, return zero

    INSERT INTO Customers (CustomerName) VALUES(@custname)
    SET @myid = @@IDENTITY()

    UPDATE Customers SET MyID = CustomerName + CONVERT(VARCHAR(10), @myid)

    --RETURN newely inserted value
    SELECT @myid

END 





如需了解更多信息,请参阅:

表格列属性(SQL Server Management Studio) [ ^ ]

创建程序 [ ^ ]

指定列的默认值 [ ^ ]

@@ IDENTITY [ ^ ]

从存储过程中返回数据 [ ^ ]



For further information, please see:
Table Column Properties (SQL Server Management Studio)[^]
CREATE PROCEDURE[^]
Specify Default Values for Columns[^]
@@IDENTITY[^]
Return Data from a Stored Procedure[^]


这篇关于在同一个表中,必须添加一个列,它自动连接id(唯一+1)和名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆