限制mysql列的整数值 [英] Limit integer value for mysql's column

查看:43
本文介绍了限制mysql列的整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将要使用

CREATE TABLE clients
(
empno     INTEGER     NOT NULL DEFAULT 7654 
cname     VARCHAR(20) NOT NULL
);

现在,我希望 empno 值介于 7000-8000 之间.如果不是,则应拒绝.第一种方法是使用 CHECK ,当然 MYSQL 会忽略它.其次是创建另一个具有可接受值的表,并将其用作外部约束或类似的东西.创建一个包含 1000 个值的表非常不方便.一定有更简单的方法,但我不知道.

Now, I want the empno value to be between 7000-8000. If not it should be rejected. First method is to use CHECK which of course MYSQL is going to ignore. Second is to create a another table with acceptable values and use it as a foreign constraint or something like that. Creating a table with 1000 values is very inconvenient. There must be an easier way but I have no idea.

推荐答案

向表中添加 INSERT/UPDATE 触发器并拒绝值不在定义范围内的任何 INSERTS.

Add an INSERT/UPDATE trigger to the table and reject any INSERTS where the value is not in the defined range.

编辑以包含示例

/*
-- ================================================
-- Template generated from Template Explorer using:
-- Create Trigger (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- See additional Create Trigger templates for more
-- examples of different Trigger statements.
--
-- This block of comments will not be included in
-- the definition of the function.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE TRIGGER <Schema_Name, sysname, Schema_Name>.<Trigger_Name, sysname, Trigger_Name> 
   ON  <Schema_Name, sysname, Schema_Name>.<Table_Name, sysname, Table_Name> 
   AFTER <Data_Modification_Statements, , INSERT,DELETE,UPDATE>
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here

END
GO
*/

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[utg_ClientsInsert]
ON [dbo].[Clients]
AFTER INSERT,UPDATE
AS
BEGIN
    SET NO COUNT ON

    IF(SELECT COUNT(*) FROM INSERTED) = 0
     BEGIN
        RETURN -- do not execute trigger if no rows
     END

    IF(SELECT COUNT(*) FROM INSERTED WHERE empno NOT BETWEEN 7000 AND 8000) > 0
     BEGIN
        -- don't allow the insert to happen
        RAISERROR('Employee # must be between 7,000 and 8,000.', 18, 1)
     END

END

GO

这篇关于限制mysql列的整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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