[英]SQL: I want to extract data from second table. As column names of second table matches with values Separated by comma of first table column
I have a table1 with one column with values seperated by comma firstname,lastname .我有一个 table1,其中一列的值由逗号firstname,lastname分隔。 I have a table2 with two column names firstname and lastname , which match with table1's single column values( firstname,lastname ).我有一个 table2 有两个列名firstname 和 lastname ,它们与 table1 的单列值( firstname,lastname )匹配。 My necessity is I want to extract data from table2 by using select statement SELECT firstname,lastname FROM table2
.我的必要性是我想通过使用选择语句SELECT firstname,lastname FROM table2
从 table2 中提取数据。 I used variables to write query.我使用变量来编写查询。
I transferred values of table1( firstname, lastname ) to @link
variable and this operation completed successfully.我将 table1( firstname, lastname ) 的值传输到@link
变量,此操作成功完成。 But when i tried to add SELECT @link FROM table2
to the query i thought i would get data of firstname and lastname of table2, But result showing a seperate no column name and value in that column as firstname,lastname .但是当我尝试将SELECT @link FROM table2
添加到查询中时,我想我会得到 table2 的名字和姓氏的数据,但是结果显示该列中没有单独的列名和值作为firstname,lastname 。
Tons of Thanks for any help!非常感谢您的帮助!
declare @link nvarchar(max)
select @link = (select [column]
from [dbo].[table1])
from [dbo].[table2]
SELECT @link FROM table2
You appear to be attempting "dynamic sql", ie you build a string that contains a select statment, then execute that string as a query.您似乎正在尝试“动态 sql”,即您构建一个包含选择语句的字符串,然后将该字符串作为查询执行。 Conventionally you will find many example that use @sql
for this, and the basic fom of this is as follows:按照惯例,您会发现很多使用@sql
的示例,其基本形式如下:
declare @sql nvarchar(max)
select @sql = N'select [column] from [dbo].[table1]'
EXEC sp_executesql @sql;
Note that the @sql contents has to be valid sql syntax.请注意,@sql 内容必须是有效的 sql 语法。 On this point your code contains 2 from
clauses and that is NOT valid, plus it isn't clear what you intended, perhaps it was meant to be a join.在这一点上,您的代码包含 2 个from
子句,这是无效的,而且不清楚您的意图是什么,也许它本来是一个连接。
declare @sql nvarchar(max)
select @sql = N'select t.[column], j.[column2]
from [dbo].[table1] as t
inner join [dbo].[table2] as j on t.id = j.fk'
EXEC sp_executesql @sql;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.