将列从一个表插入另一个表的过程

时间:2014-03-20 07:16:57

标签: sql sql-server sql-server-2005

我想将现有表中的日期,服务和service_count列插入到新表中。我想用一个程序来做它但它没有用。


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROC  [dbo].[SP_INSERTCOLOUMNS]     
AS       
BEGIN
            DECLARE @SQLS NVARCHAR(MAX)

            SET @SQLS = 'insert into test(date,service,service_count) 
                                 select date,service,count(service) from tbl_OBD_CDRS 
                                 group by date,service'
            PRINT @SQLS

            EXEC SP_EXECUTESQL @SQLS            
            PRINT 'INSERTED SUCCESSFULLY'
END

如果我独立运行insert命令,它可以正常工作。如果我使用这个程序运行它,它说Command(s)已成功完成,但表中没有进行任何更改" test"。

2 个答案:

答案 0 :(得分:0)

我的脚本中没有任何问题。为什么不尝试检查测试表中的计数。查看测试表中是否没有记录增加。

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROC  [dbo].[SP_INSERTCOLOUMNS]     
AS       
BEGIN
            select date,service,count(service) from tbl_OBD_CDRS 
                                 group by date,service

            DECLARE @SQLS NVARCHAR(MAX)

            SET @SQLS = 'insert into test(date,service,service_count) 
                                 select date,service,count(service) from tbl_OBD_CDRS 
                                 group by date,service'
            PRINT @SQLS

            EXEC SP_EXECUTESQL @SQLS            
            PRINT 'INSERTED SUCCESSFULLY'
END

尝试在SQL Server上运行此命令并发布结果。

EXEC [dbo].[SP_INSERTCOLOUMNS] 

答案 1 :(得分:0)

ALTER PROC  [dbo].[SP_INSERTCOLOUMNS]     
AS       
BEGIN
           -- select date,service,count(service) from tbl_OBD_CDRS 
               --                  group by date,service



            insert into test(date,service,service_count) 
            select date,service,count(service) from tbl_OBD_CDRS Group by date,service


            PRINT 'INSERTED SUCCESSFULLY'
END

如果表/数据类型中的任何错误直接抛出

,请使用此方法