日期:2014-05-19  浏览次数:20667 次

如何创建如下的存储过程
第一个表today的字段(id\amount\money\store),其中store有唯一性,现在它共有1000个数字,另外在数据库中还有1000个表就是以store里面的数字为表名。请问如何将today中的数据一次性导入到对应的store表里面。
假设数据如下:
id     amount     money     store
1       100           100.00       1
2       135           55.00         3
3       6008         8009.00     8
如何一次性将上面的第一行数据添加到表1(1就是表名),第二行数据添加到表3,第三行数据添加到表8

------解决方案--------------------
看看我写的

CREATE table today
(id nvarchar(50),
amount nvarchar (50),
money nvarchar (50),
store nvarchar (50))

CREATE table [1]
(id nvarchar(50),
amount nvarchar (50),
money nvarchar (50))

CREATE table [3]
(id nvarchar(50),
amount nvarchar (50),
money nvarchar (50))

CREATE table [8]
(id nvarchar(50),
amount nvarchar (50),
money nvarchar (50))

INSERT INTO today
SELECT
1 , 100 , 100.00 , 1
UNION SELECT
2 , 135 , 55.00 , 3
UNION SELECT
3 , 6008 , 8009.00 , 8


--创建存储过程实现你说的功能
if exists (select * from dbo.sysobjects where id = object_id(N '[dbo].[ExportToday] ') and OBJECTPROPERTY(id, N 'IsProcedure ') = 1)
drop procedure [dbo].[ExportToday]
GO

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE [dbo].[ExportToday]
AS
BEGIN

DECLARE @Store nvarchar(50)
DECLARE @SQL nvarchar(500)

DECLARE
Store_Today
Cursor
FOR
SELECT DISTINCT Store FROM TODAY

open Store_Today
fetch
next
from Store_Today
into @Store

WHILE @@FETCH_STATUS = 0
BEGIN
print @Store
if exists(SELECT name FROM sysobjects WHERE (name =@Store) AND (xtype = 'u ') )
begin
set @SQL= ' insert into [ '+@Store+ '] select id,amount,money from today where Store= '+@Store
print @SQL
execute sp_executesql @SQL

end

fetch
next
from Store_Today
into @Store


END

close Store_Today
deallocate Store_Today


END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO


然后执行这个存储过程就可以了
exec ExportToday

------解决方案--------------------
上面这个的存储过程写的ok,不过如果在判断有没有表
if exists(SELECT name FROM sysobjects WHERE (name =@Store) AND (xtype = 'u ') )
的时候,如果没有的话,那么新建一个表就更好了

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE [dbo].[ExportToday]
AS
BEGIN

DECLARE @Store nvarchar(50)
DECLARE @SQL nvarchar(500)

DECLARE
Store_Today
Cursor
FOR
SELECT DISTINCT Store FROM TODAY

open Store_Today
fetch
next
from Store_Today
into @Store

WHILE @@FETCH_STATUS = 0
BEGIN
print @Store
if exists(SELECT name FROM sysobjects WHERE (name =@Store) AND (xtype = 'u ') )
begin
set @SQL= ' inser