从查询结果更新多个表

时间:2019-03-02 14:16:59

标签: sql-server

是否可以从查询结果中更新多个表?

我尝试使用游标。但是它仍然无法正常工作。

这是代码:

CREATE TABLE `users`
(
  user_id    INT  NOT NULL  AUTO_INCREMENT  PRIMARY KEY,
  user_name  VARCHAR(20)
)
;

CREATE TABLE `connections`
(
  `user_id`    INT  NOT NULL,
  `friend_id`  INT  NOT NULL,
  `show_posts` BOOL,
  PRIMARY KEY(`user_id`, `friend_id`)
)
;

CREATE TABLE `posts`
(
  `post_id`   INT  NOT NULL  AUTO_INCREMENT  PRIMARY KEY,
  `user_id`   INT  NOT NULL,
  `content`   TEXT(2000)
)
;

INSERT INTO `users`
  (`user_name`)
VALUES
  ('Tom'  ),
  ('Sarah'),
  ('Ben'  )
;

INSERT INTO `connections`
VALUES
  (1,2, true ), -- Tom/Sarah, Tom wants Sarah's posts
  (2,1, false), -- Sarah/Tom, Sarah does not want Tom's posts
  (1,3, false), -- Tom/Ben,   Tom does not want Ben's posts
  (3,1, true )  -- Ben/Tom,   Ben does not want Tom's posts
;

INSERT INTO `posts`
  (`user_id`, `content`)
VALUES
  (1, 'First post by Tom.'   ),
  (2, 'First post by Sarah.' ),
  (1, 'Second post by Tom.'  ),
  (3, 'First post by Ben.'   ),
  (3, 'Second post by Ben.'  ),
  (2, 'Second post by Sarah.'),
  (3, 'Third post by Ben.'   )
;

1 个答案:

答案 0 :(得分:1)

假设

我想OP试图为具有列holder.dlbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Uri uri = Uri.parse(queryVersiones.getDl_link()); Intent intent = new Intent(Intent.ACTION_VIEW, uri); mContext.startActivity(intent); } }); 的所有表动态构建和执行SQL代码

解决方案

解决方案(其中之一)可能是:

  1. 创建的SQL表达式的构建光标
  2. 在周期Code1中创建表达式

示例代码

exec

警告

我没有测试它(原因是-我没有类似的数据库)-请当心。

更新

更简单的是像这样修改OP代码:

DECLARE @sql_code varchar(max)

DECLARE code_cursor CURSOR FOR
SELECT DISTINCT 
       'UPDATE '+ TABLE_NAME + ' SET Code1= Code + ''_'' + Type;' AS SQL_CODE
     FROM 
         information_schema.columns -- WHERE column_name = 'Code1';

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @sql_code

WHILE @@FETCH_STATUS = 0
BEGIN 
    exec(@sql_code)

    FETCH NEXT FROM db_cursor INTO @TableName
END
CLOSE db_cursor
DEALLOCATE db_cursor