将检查约束值保存到变量

时间:2013-09-10 20:04:54

标签: sql-server constraints

我以这种方式获得表检查约束定义:

select a.CHECK_CLAUSE
from INFORMATION_SCHEMA.CHECK_CONSTRAINTS a,INFORMATION_SCHEMA.TABLE_CONSTRAINTS b
where b.TABLE_NAME = 'table name'

对于我的示例,假设运行此查询将返回:

[([depname]='mathematics' OR [depname]='electronics' OR [depname]='computer science')]

如何将检查约束中指定的值分配给变量?即计算机科学,数学和电子学?

1 个答案:

答案 0 :(得分:1)

看起来你正在收到一个字符串。您可以做的是将字符串拆分为OR的实例并将其存储在数组中,然后运行数组并拆分=上的每个元素以隔离值。因此,如果您要在PHP中执行此操作,则代码可能如下所示:

// For reasons of simplicity we will assume the result is stored in $result,
// and the leading [( and trailing )] have already been removed
$values = array();
$resultsplit = explode(' OR ', $result);

/* $resultsplit is now an array:
 * $resultsplit[0] = "[depname]='mathematics'"
 * $resultsplit[1] = "[depname]='electronics'"
 * $resultsplit[2] = "[depname]='computer science'"
 */

if ($result != '') {
    foreach ($resultsplit as $rs) {
        $rsparts = explode('=', $rs);

        /* $rsparts is now an array. On the first element:
         * $rsparts[0] = "[depname]"
         * $rsparts[1] = "'mathematics'"
         * So all we need to do is stick $rsparts[1] into $values
         */

        $values[] = $rsparts[1];
    }
}

这会将所有值放入数组$values(包括开头和结尾的单引号),以便随意使用,无论有多少。如果PHP不是您可以使用的语言,则相同的方法仍然可以使用您选择的语言。