Je souhaite ajouter une contrainte sur une colonne dépendant d'une colonne d'une table différente. Par exemple, si dans la table T1 j'ai une colonne string str1, et sur la table T2 j'ai une chaîne str2 str2, je veux que str1 soit nul à l'exception de quand srt2 - "ok".Constraint - SQL Server
0
A
Répondre
0
vous pouvez utiliser un script de déclenchement (avant l'exécution) sur t1 qui vérifie lorsqu'une chaîne est inséré dans str1, si str2 est égal à « ok »
1
Vous ne pouvez pas utiliser SELECT dans une contrainte, mais un utilisateur fonction définie est autorisée. Vous pouvez donc créer une fonction pour récupérer str2 à partir de T2. Voici un exemple de configuration:
create table t1 (id int, str1 varchar(max))
create table t2 (str2 varchar(10))
go
create function dbo.GetStr2() returns varchar(10)
as
begin
declare @retval varchar(10)
select @retval = str2 from t2
return @retval
end
go
alter table t1 add constraint CheckStr2Constraint
check (str1 is null or dbo.GetStr2() = 'ok');
Vous pouvez tester cela comme:
insert into t2 values ('ok')
insert into t1 values (1,'test') -- Succeeds
insert into t1 values (1,null) -- Succeeds
update t2 set str2 = 'not ok'
insert into t1 values (1,'test') -- Fails
insert into t1 values (1,null) -- Succeeds
Le troisième INSERT échouera, car str2 est « pas correct », et vous insérez une chaîne non nulle. Le message d'erreur ressemblera à:
The INSERT statement conflicted with the CHECK
constraint "CheckStr2Constraint".
Questions connexes
- 1. Oracle Check Constraint
- 2. Comment obtenir le nom de Constraint?
- 3. Télécharger SQL SERVER AGENT - Microsoft SQL Server
- 4. Authentification SQL Server dans SQL Server 2008
- 5. SQL Server
- 6. Erreurs SQL Server 2000 Server
- 7. SQL Server 2005 Express installé après SQL Server 2008 Express
- 8. SQL Server 2008 réplication vers SQL Server 2000
- 9. Rétrogradation de SQL Server 2008 vers SQL Server 2005
- 10. SQL Server Par question SQL Server 2005 CE
- 11. Modification du SQL Server 2005 Server
- 12. Contrainte minuscule - SQL Server
- 13. SQL Server C++ natif
- 14. SQL Server 2008 SP1
- 15. SQL Server VARCHAR (10)
- 16. SQL Server - PIVOT
- 17. SQL server timeout
- 18. Ports SQL Server
- 19. SQL Server Metrics
- 20. SQL SERVER 2005
- 21. COBOL à SQL Server
- 22. SQL Server BETWEEN problème
- 23. SQL Server 2008 R2
- 24. Organisation d'objet SQL Server
- 25. SQL Server: Join
- 26. Sql Server Reporting services
- 27. Réplication SQL Server
- 28. SQL Server rand() agrégat
- 29. SQL Server 2005 xp_cmdshell
- 30. SQL Server Random Sort