我想用哪个概念来使用SQL Server 2012获取以下输出

时间:2016-08-17 06:03:58

标签: sql-server

我的表格包含以下数据

 ID  | Name
 --- | ---------
 1   | Apple
 2   | Microsoft
 3   | Samsung       and so on...

就我而言,输入是' 1,2,3'。

我需要的输出是' Apple,Microsoft,Samsung'。

4 个答案:

答案 0 :(得分:2)

SELECT STUFF((
       SELECT ','+ Name 
       FROM MyTable
       WHERE ID in (1, 2, 3)
       FOR XML PATH('')
    ), 1, 1, '') AS Names

结果:

  

苹果,微软,三星

答案 1 :(得分:1)

您可以使用package collectionFramework; import java.util.Iterator; import java.util.LinkedList; public class LinkedListDemo{ public static void main(String[] args) { Demo obj = new Demo(); obj.addToList(); obj.displayList(); } } class Demo{ LinkedList<String> al; Iterator<String> itr; Demo(){ al = new LinkedList<String>(); itr = al.iterator(); } void addToList(){ al.add("Aniruddha"); al.add("Hitesh"); al.add("Rahul"); al.add("Kshitij"); } void displayList(){ while(itr.hasNext()){ System.out.println(itr.next()); } } }

XML PATH

结果看起来像SELECT ( SELECT T.Name + ', ' FROM Tbl T WHERE Id in (1, 2, 3) FOR XML PATH ('') ) DesiredOutput

答案 2 :(得分:0)

USE [Database Name]

SELECT COLUMN_NAME,* 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName'

答案 3 :(得分:0)

由于SQL服务器在运行时不支持输入,您可以创建存储过程并在执行时传递输入值。或者只是运行以下查询。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>demo.tomcat</groupId>
    <artifactId>jvmroute-demo</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>tomcat-jvmroute</name>
    <description>demo jvmroute issues</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>