从一个表插入另一个表的问题!

时间:2011-06-09 17:32:01

标签: c# asp.net sql

    StringBuilder insertCommand = new StringBuilder();

    insertCommand.Append("DECLARE @TopicsId int; INSERT INTO Topics(Theme,Topics,Date)");
    insertCommand.Append("VALUES(@topic,@subTopic,GETDATE())");
    insertCommand.Append("SET @TopicsId = SCOPE_IDENTITY()");

    insertCommand.Append("INSERT INTO Threads(UsersID,TopicsID,Date,ThreadTitle,ThreadParagraph,ThreadClosed,Views,Replies,PageNumber)");
    insertCommand.Append(" SELECT u.UsersID,@TopicsID,GETDATE(),@questionTitle,@questionParagraph,0,0,0,FLOOR(Count(t.TopicsID)/20)"); // i think the problem is in the u.UserID in this line
    insertCommand.Append(" FROM Threads AS d ");
    insertCommand.Append(" INNER JOIN Topics AS t ON d.TopicsID=t.TopicsID");
    insertCommand.Append(" INNER JOIN Users AS u ON u.UsersID=t.UsersID");

我想从Users表UsersID插入Threads表。但是抛出一个异常,说没有名为UsersID的列。我认为它确实将u.UserID作为参数并将其放入Threads UsersID中,因为我在Threads中有一个名为usersID的列。有解决方案吗?

2 个答案:

答案 0 :(得分:0)

你拼错了一列(UsersID vs UserID)吗?

如果您可以直接访问数据库(例如,通过SQL Management Studio),请尝试仅运行选择并正确格式化SQL,以便向您显示有问题的行号,例如

SELECT 
  u.UsersID,@TopicsID,GETDATE(),@questionTitle,@questionParagraph,0,0,0,FLOOR(Count(t.TopicsID)/20))
FROM 
  Threads AS d
INNER JOIN 
  Topics AS t ON d.TopicsID=t.TopicsID
INNER JOIN 
  Users AS u ON u.UsersID=t.UsersID

答案 1 :(得分:-1)

Insert into threads(....)
Values (blablabla,blablabla)

INSERT需要VALUES关键字

我在陈述中没有看到它