SQL值对列值的约束取决于其他列的值

时间:2015-06-12 09:15:19

标签: sql sql-server constraints check-constraints

首先,我有一个简单的[SomeType]表,列[ID][Name]

我还有[SomeTable]表,其中的字段如下:

[ID], 
[SomeTypeID] (FK), 
[UserID] (FK), 
[IsExpression]

最后,我必须在数据库层上建立一个约束:

  • 表示具体[SomeType]个ID(实际上,除了一个以外的所有ID),
  • 表示同一UserID
  • 只有一个条目的[IsExpression]等于1 (IsExpression属于BIT类型)

我不知道它是否复杂,但我不知道如何写它。你会如何实现这样的约束?

1 个答案:

答案 0 :(得分:1)

您可以使用过滤索引执行此操作:

@echo off
cls
title Skype

:MENU
echo ==================================================================
echo.
echo [1]    Launch Skype
echo [2]    Close Skype
echo [3]    Check status
echo.
echo Note: Turn Off Automatic Update to avoid Updater.exe running
echo Note: Q to Quit
echo ==================================================================

:Option
SET /P INPUT="Choose an option:"
IF /I '%INPUT%'=='1' GOTO Launch
IF /I '%INPUT%'=='2' GOTO Close
IF /I '%INPUT%'=='3' GOTO CheckStatus
IF /I '%INPUT%'=='Q' GOTO Quit

:Launch
echo.
echo Launching Skype... Please wait few seconds.
start "" /b /min /LOW Skype.exe
ping 192.0.2.2 -n 1 -w 5000>nul 2>nul
tasklist /FI "IMAGENAME eq Skype.exe" 2>NUL | find /I /N "Skype.exe">NUL
if "%ERRORLEVEL%"=="0" echo Skype is running.                           
if "%ERRORLEVEL%"=="1" echo Skype is closed.
echo.
GOTO Option

:Close
echo.
echo Closing Skype... Please wait few seconds.
taskkill /f /im Skype.exe>NUL
ping 192.0.2.2 -n 1 -w 2000>nul 2>nul
tasklist /FI "IMAGENAME eq Skype.exe" 2>NUL | find /I /N "Skype.exe">NUL
::If Skype if closed, status is running... problem?
if "%ERRORLEVEL%"=="0" echo Skype is running.                           
if "%ERRORLEVEL%"=="1" echo Skype is closed.
echo.
GOTO Option

:CheckStatus
echo.
echo Checking Skype status... Please wait few seconds.
ping 192.0.2.2 -n 1 -w 1000>nul 2>nul
tasklist /FI "IMAGENAME eq Skype.exe" 2>NUL | find /I /N "Skype.exe">NUL
if "%ERRORLEVEL%"=="0" echo Skype is running.                           
if "%ERRORLEVEL%"=="1" echo Skype is closed.
echo.
GOTO Option

:Quit
EXIT

或:

CREATE UNIQUE NONCLUSTERED INDEX [IDX_SomeTable] ON [dbo].[SomeTable]
(
    [UserID] ASC
)
WHERE ([SomeTypeID] <> 1 AND [IsExpression] = 1)

取决于您想要实现的目标。在一个用户中只有一个CREATE UNIQUE NONCLUSTERED INDEX [IDX_SomeTable] ON [dbo].[SomeTable] ( [UserID] ASC, [SomeTypeID] ASC ) WHERE ([SomeTypeID] <> 1 AND [IsExpression] = 1) 而不考虑[IsExpression] = 1,或者您只想在一个用户中使用一个[SomeTypeID]而只需要一个[IsExpression] = 1