SQL将一行多列数据合并成一列

SQL将一行多列数据合并成一列

2023年7月13日发(作者:)

SQL将⼀⾏多列数据合并成⼀列由于最近在做项⽬的时候,要对数据库中⼀⾏很多列个数据进⾏求和,便在⽹上查了⼀下,⾸先要⽤到动态SQL语句,动态sql感觉就是类似于拼接sql字符串动态语句基本语法

1 :普通SQL语句可以⽤exec执⾏

Select * from tableName

exec('select * from tableName')

exec sp_executesql N'select * from tableName' -- 请注意字符串前⼀定要加N2:字段名,表名,数据库名之类作为变量时,必须⽤动态SQLdeclare @fname nvarchar(20)

set @fname = 'FiledName'

Select @fname from tableName -- 错误,不会提⽰错误,但结果为固定值FiledName,并⾮所要。

exec('select ' + @fname + ' from tableName') -- 请注意 加号前后的 单引号的边上加空格如果设置字符串变量,应该把它设置成

nvarchar,

但是我在SQL SERVER2014上⾯⽤varchar照样也可以接下来就是具体的执⾏代码select 列1+列2+...+列30 from tabledeclare @sql nvarchar(1000)set @sql=''select @sql=@sql+'+isnull('+name+',0)'--inull(paras1,paras2)函数⽤来判断是否为空,如果为空⽤paras2替换from syscolumns

where id=object_id('表名') and xtype=56 --56表⽰整型

set @sql=stuff(@sql,1,1,'')--⽤于将第⼀加号替换掉,这⼀句代码不可以少否则会出现错误print ('select '+@sql+' from 表名')exec ('select '+@sql+' from 表名')例如如上⾯的⼀张表格我要对其进⾏求和:use testgodeclare @sql varchar(1000)set @sql=''select @sql=@sql+'+isnull('+name+',0)'from syscolumns

where id=object_id('tb1') and xtype=56--对应整型set @sql=stuff(@sql,1,1,'')print ('select '+@sql+' from tb1')

exec ('select '+@sql+' from tb1')上⾯就是求得的结果,因为我把id和id1这两列设成了整型和浮点型所只计算了第⼀列如果只想求⼀⾏的和可以在select 语句⾥加上TOP 函数,就可以了如果我们想把执⾏动态SQL 的结果赋值给另⼀变量的话,就需要执⾏存储过程了,在执⾏下⾯的存储过程的时候如果是字符串类型的话应该都设置为nvarchar这样可以避免出错EXEC sp_executesql @stmt= ,--类似存储过程主体@params = , --类似存储过程参数部分,声明参数类型 --类似存储过程调⽤,为参数赋值,参数值要和参数顺序要⼀⼀对应,也可以通过为参数指明参数值的⽅式为其赋值附上我写的代码:declare @sum int,@sql nvarchar(1000),@num int,@sql1 nvarchar(100)

set @sql=''

select @sql=@sql+'+isnull('+name+',0)'

from syscolumns

where id=object_id('tb1') and xtype=56

set @sql=stuff(@sql,1,1,'')--print ('select '+@sql+' from 表名')

set @sql1= 'select @sum=(select top(1) id from tb1)'

set @sql1='select @sum=(select top 1 '+@sql+' id from tb1)'

exec sp_executesql @sql1,N'@sum int output',@num output

select @numPS: syscolumns是sqlserver中的⼀个系统表,⽤来记录sqlserver中字段信息的。也就是在数据库⾥所有表格⾥ 的字段的信息但是创建的临时表⾥的字段的信息并没有存储在这个系统表⾥xtype 类型34 image35 text36 uniqueidentifier48 tinyint52 smallint56 int58 smalldatetime59 real60 money61 datetime62 float98 sql_variant99 ntext104 bit106 decimal108 numeric122 smallmoney127 bigint165 varbinary167 varchar173 binary175 char189 timestamp231 sysname231 nvarchar239 nchar

发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1689246116a225603.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信