C#SQL INSERT INTO查询和显示结果

时间:2011-11-15 03:27:53

标签: sql sql-server database tsql

我正在使用VS2005和SQL Server 2005。

我正在尝试执行连接3个sql表的多个INSERT INTO SQL语句。

3个表格是:

  • Table1UserID, Username
  • Table2UserID, Status
  • Table3UserID, Username, Issue

以下是我需要执行的检查:

  1. Table1中存在的用户应存在于Table2

  2. Table1中存在的用户STATUS=DELETE

  3. 中不应有Table2
  4. STATUS=DELETE

  5. Table2中没有Table1的用户

    目前我只有一个SELECT语句,可以满足上述3个查询,而无需在第3个表中添加:

    SELECT *
    FROM table1 t1
    FULL OUTER JOIN table2 t2 ON t1.userid = t2.userid
    WHERE (t2.userid IS NULL AND t1.userid IS NOT NULL)
    OR (t2.status = 'DELETE' AND t1.userid IS NOT NULL)
    OR (t2.userid IS NOT NULL AND t2.status <> 'DELETE' AND t1.userid IS NULL)
    

    对于上面的每项检查,我想INSERT将结果导入Table3并使用唯一的ISSUE变量(例如,对于第1号检查,ISSUE=User exist in t1 but not t2)< / p>

    目前我正在尝试形成一个将3个表连接在一起的查询,对于第一个检查t2.userid IS NULL AND t1.userid IS NOT NULL找到的每个结果,它会在Table3中插入一个新行。但是我在使用SQL查询时遇到了一些问题。

    INSERT INTO Table3 (userid, username, issue) 
    VALUES (t1.userid, t1.username, 'user not found in t2')
    FULL OUTER JOIN table2 t2 ON t1.userid = t2.userid
    WHERE (t2.userid IS NULL AND t1.userid IS NOT NULL)
    

    非常感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

我没有这些表进行测试,因此语法将会很接近:

COALESCE的{​​{1}}将确保您在列中插入值,因为您不确定该值是否存在于Table1或Table2中

我还使用了UserId语句的where子句来填充CASE列。您可以更新文本以适合您的应用程序。

Issue

答案 1 :(得分:2)

1.
    Insert in to Table3(userid,issue)
        SELECT t1.userid,'check no.1'
        FROM table1 t1
        FULL OUTER JOIN table2 t2 ON t1.userid = t2.userid
        where t1.userid not null and t2.userid is null
2.
    Insert in to Table3(userid,issue)
        SELECT t1.userid,'check no.2'
        FROM table1 t1
        inner JOIN table2 t2 ON t1.userid = t2.userid
        where t2.status = 'DELETE'

3.
    Insert in to Table3(userid,issue)
        SELECT t2.userid,'check no.3'
        FROM table1 t1
        right outer JOIN table2 t2 ON t1.userid = t2.userid
        where t2.status = 'DELETE' and t1.userid is null