Как создать проверочное ограничение между двумя столбцами в SQL?

Вероятно, вам следует использовать цикл для этого, даже когда вы знаете число, просто чтобы сделать код более понятным (например, чтобы вам не приходилось переписывать логику в случае изменения числа).

[ 1110] Например, вы можете динамически составить список таких вопросов:

    const questionsArray = [
        ["What's my favorite color?"], 
        ["Describe my favorite toy."]
     ];

    const mainContainer = document.querySelector("#mainContainer");
    for(let i = 0; i < questionsArray.length; i++){

      // Makes a node to hold the question text
      let qTextNode = document.createTextNode(questionsArray[i]);

      // Makes a paragraph element to display the question text in
      let qParagraph = document.createElement("p");

      // Makes a div element to hold this question and all its possible answers
      let qContainer = document.createElement("div");

      // Gives the container some distinguishing attributes
      qContainer.classList.add("question");
      qContainer.id = (i + 1);

      // Puts the text in the paragraph
      qParagraph.appendChild(qTextNode);

      // Puts the paragraph in the container
      qContainer.appendChild(qParagraph);

      // Adds the container (and everything inside it) to the page
      mainContainer.appendChild(qContainer);

    }
    // Prints out the HTML we just created
    console.log(mainContainer.outerHTML.split("><").join(">\n<"));
<div id="mainContainer"></div>

. Как и во многих случаях, когда вы запускаете сниппет, но, как вы можете видеть в консоли, теперь у вас есть организованная структура для всех ваших вариантов ответов, чтобы жить. Позже может появиться код javascript и найти конкретные элементы на вашей странице, как и стили CSS . [+1112]

Вот вычурная версия, которая добавляет текст ответа на каждый вопрос. Для этого нам нужен цикл внутри цикла (поскольку у каждого вопроса есть несколько вариантов ответов, которые мы хотим динамически добавить):

const questionsArray = [
        ["What's my favorite color?"], 
        ["Describe my favorite toy."]
      ];
const answersArray = [
        ["black", "green", "yellow", "orange"], 
        ["big","small","long"], 
      ];

    // Stuff you saw in the previous snippet
    const mainContainer = document.querySelector("#mainContainer");
    for(let i = 0; i < questionsArray.length; i++){
      let qTextNode = document.createTextNode(questionsArray[i]);
      let qParagraph = document.createElement("p");
      let qContainer = document.createElement("div");
      qContainer.classList.add("question");
      qContainer.id = (i + 1);
      qParagraph.appendChild(qTextNode);
      qContainer.appendChild(qParagraph);
    
      // Makes an "ordered list" element to hold the choices
      let aList = document.createElement("ol");
      
      // Letters array will be used for item IDs
      let letters = "A,B,C,D,E,F,G,H,I,J".split(",");          

      // A nested loop to add the choices
      for(let j = 0; j < answersArray[i].length; j++){

        // Makes a textNode to hold the current choice
        let aTextNode = document.createTextNode(answersArray[i][j]);

        // Makes a list-item element to display the choice text in
        let aItem = document.createElement("li");

        // Gives the item an id using question number & answer letter
        aItem.id = (i + 1) + letters[j];

        // Puts the choice text in the item
        aItem.appendChild(aTextNode);

        // Puts the item in the list
        aList.appendChild(aItem);
      }

    // Done looping through choices, this adds the list to the question container
    qContainer.appendChild(aList);

  // And... we're back to stuff from the previous snippet
    mainContainer.appendChild(qContainer);
  }
  console.log(mainContainer.outerHTML.split("><").join(">\n<"));
/* The visible letters for the list items come from here, not from the script */
ol{ list-style-type: upper-alpha; }
.question{ margin-top: 25px; }
<div id="mainContainer"></div>

5
задан skaffman 31 January 2010 в 17:07
поделиться

3 ответа

Это могло бы (вероятно, сделать), зависят от базы данных, которую Вы используете.

По сравнению с синтаксисом оракула (например, здесь: http://www.techonthenet.com/oracle/check.php), то, что Вы пропускаете, могло бы быть'', между ПУСТЫМ УКАЗАТЕЛЕМ и ОГРАНИЧЕНИЕМ

6
ответ дан 14 December 2019 в 04:48
поделиться

Проблема состоит в том, что Вы определили его как ограничение целостности уровня столбца, но это ссылается на другие столбцы. Необходимо определить ограничение на уровне таблицы.

ALTER TABLE bp
    ADD CONSTRAINT CK_limit CHECK ( upperlimit > lowerlimit)
1
ответ дан 14 December 2019 в 04:48
поделиться

Здесь является надлежащим SQL-запрос...

CREATE TABLE bp (bpid VARCHAR(5),
FOREIGN KEY (bpid) REFERENCES designation(desigid), 
upperlimit DECIMAL(10,2) NOT NULL,
lowerlimit DECIMAL(10,2) NOT NULL,
increment DECIMAL(10,2) NOT NULL,
CONSTRAINT llvalid CHECK (upperlimit > lowerlimit));

Отметьте запятую после NOT NULL и ОГРАНИЧЕНИЯ в последней строке.

1
ответ дан 14 December 2019 в 04:48
поделиться
Другие вопросы по тегам:

Похожие вопросы: