带字符串输入参数的SQL查询

时间:2016-10-19 12:00:09

标签: sql sql-server

我需要sql查询(可能是动态的?),它将处理我的输入参数:

  • @Data - 数据,
  • @Fields - 列名,
  • @Types - 数据类型

按标准字符分隔的行。通过TAB分离列。

输入数据:

DECLARE @Data nvarchar(max) = N
   '1             cat fish
    2             dog meat
    3             chicken corn
    4             cow herb
    5             pig feed
    6             human              all'

DECLARE @Fields nvarchar(555) = N'ID Object  FoodType'

DECLARE @Types nvarchar(555) = N'int nvarchar(36)      nvarchar(36)'

我需要的结果:

ID  Object  FoodType
1   cat     fish
2   dog     meat
3   chicken corn
4   cow     herb
5   pig     feed
6   human   all

提前致谢

1 个答案:

答案 0 :(得分:0)

declare @t table (id int, name  varchar(50))

insert into @t (id,name) values( 1    ,'cat fish')
insert into @t (id,name) values( 2    ,'dog meat')
insert into @t (id,name) values( 3    ,'chicken corn')
insert into @t (id,name) values( 4    ,'cow herb')
insert into @t (id,name) values( 5    ,'pig feed')
insert into @t (id,name) values( 6    ,'human all')


select 
    case when CHARINDEX(' ',name)>0 
         then SUBSTRING(name,1,CHARINDEX(' ',name)-1) 
         else name end  Object , 
    CASE WHEN CHARINDEX(' ',name)>0 
         THEN SUBSTRING(name,CHARINDEX(' ',name)+1,len(name))  
         ELSE NULL END as FoodType
from @t