简体   繁体   English

如何创建存储过程以在 Sql server 中创建表,其中表的名称将按年份更改,例如 Order2019

[英]How to make a store procedure to create table in Sql server in which name of table will be changed by year e.g Order2019

I'm making a desktop application in C#.Net, and want to make a store procedure in Sql server.我正在用 C#.Net 制作一个桌面应用程序,并想在 Sql 服务器中制作一个存储过程。 It should first check if the table is exists or not if exists it should insert values in the table else create table and table name will taken from the winForm dynamically like in 2019 table should table2019 next this it should create table2020 and so on.它应该首先检查表是否存在如果存在它应该在表中插入值否则创建表和表名将从winForm动态获取,就像在2019表中应该是table2019接下来它应该创建table2020等等。

CREATE PROCEDURE SaveOrderByYear(@tableName varchar(50),@SaleOrderID    INT,
    @CustomerID     INT,
    @CustomerName   NVARCHAR(100),
    @CustomerNameU  NVARCHAR(100),
    @SaleManID      INT,
    @SaleManName    NVARCHAR(100),
    @SaleManNameU   NVARCHAR(100),
    @SaleExecutiveID        INT,
    @SaleExecutiveName  NVARCHAR(100),
    @SaleExecutiveNameU NVARCHAR(100),
    @SaleMonth      INT,
    @SaleYear       INT,
    @SaleDate       DATE,
    @SaleTime       TIME(2),
    @CreatedBy      INT,
    @CreatedName    NVARCHAR(100),
    @CreatedNameU   NVARCHAR(100),
    @CreatedDate    DATE) as begin

IF (object_id(@tableName, 'U') is null)
begin declare @query varchar(1000); set @query = 'create table ' + @tableName + ' (SaleOrderID INT NOT NULL PRIMARY KEY,
                                                                                   CustomerID   INT NOT NULL,
                                                                                   CustomerName NVARCHAR(100) NOT NULL,
                                                                                   CustomerNameU NVARCHAR(100) NOT NULL,
                                                                                   SaleManID INT NOT NULL,
                                                                                   SaleManName NVARCHAR(100) NOT NULL,
                                                                                   SaleManNameU NVARCHAR(100) NOT NULL,
                                                                                   SaleExecutiveID INT NOT NULL,
                                                                                   SaleExecutiveName NVARCHAR(100) NOT NULL,
                                                                                   SaleExecutiveNameU NVARCHAR(100) NOT NULL,
                                                                                   SaleMonth INT NOT NULL,
                                                                                   SaleYear  INT NOT NULL,
                                                                                   SaleDate  DATE NOT NULL,
                                                                                   SaleTime  TIME(2) NOT NULL,
                                                                                   CreatedBy INT NOT NULL,
                                                                                   CreatedName NVARCHAR(100) NOT NULL,
                                                                                   CreatedNameU NVARCHAR(100) NOT NULL,
                                                                                   CreatedDate DATE NOT NULL,
                                                                                   UpdatedBy  INT NULL,
                                                                                   UpdatedName NVARCHAR(100) NULL,
                                                                                   UpdatedNameU NVARCHAR(100) NUll,
                                                                                   UpdatedDate DATE NULL
                                                                                    )' exec (@query) end print @query

set @query = 'insert into ' + @tableName + ' (SaleOrderID,CustomerID,CustomerName,CustomerNameU,
                SaleManID,SaleManName,SaleManNameU,SaleExecutiveID,SaleExecutiveName,SaleExecutiveNameU,
             SaleMonth,SaleYear,SaleDate,SaleTime,CreatedBy,CreatedName,CreatedNameU,CreatedDate,UpdatedBy,
             UpdatedName,UpdatedNameU,UpdatedDate) values (@SaleOrderID,@CustomerID,@CustomerName,@CustomerNameU,@SaleManID,@SaleManName,@SaleManNameU,@SaleExecutiveID,
    @SaleExecutiveName,@SaleExecutiveNameU,@SaleMonth,@SaleYear,@SaleDate,@SaleTime,@CreatedBy,@CreatedName,
    @CreatedNameU,@CreatedDate)' print @query

exec (@query) end

I used this code but it return some errors.. Like我使用了这段代码,但它返回了一些错误..喜欢

Incorrect syntax near NVAR Must Declare scalar variable @SalesOrderID NVAR 附近的语法不正确必须声明标量变量 @SalesOrderID

You can achieve this requirement in SQL server using a dynamic query (execute statement).您可以使用动态查询(执行语句)在 SQL Server 中实现此要求。 You need to build a query in SQL stored procedure dynamically, either you can pass the table name as a parameter or you can build the table name inside the stored procedure itself.您需要在 SQL 存储过程中动态构建查询,可以将表名作为参数传递,也可以在存储过程本身内部构建表名。 below is the sample code to achieve your requirement.以下是实现您的要求的示例代码。 The stored procedure taking table name as a parameter and checking if the table does not already exist then will create the table and thereafter insert the data in that table.存储过程以表名作为参数并检查该表是否已存在,然后将创建该表,然后将数据插入该表中。 this is just a sample to demonstrate how this feature can be built.这只是演示如何构建此功能的示例。 You can modify it further the table structure and the insert statement based on data which you need to insert.您可以根据需要插入的数据进一步修改表结构和插入语句。 Please feel free to ask if you have any further questions.如果您有任何其他问题,请随时提问。

Sample code示例代码

create procedure Proc1(@tableName varchar(50)) as begin创建过程 Proc1(@tableName varchar(50)) 作为开始

IF (object_id(@tableName, 'U') is null) IF (object_id(@tableName, 'U') 为空)
begin declare @query varchar(1000);开始声明@query varchar(1000); set @query = 'create table ' + @tableName + ' (field1 varchar(100) )' exec (@query) end print @query set @query = '创建表' + @tableName + ' (field1 varchar(100) )' exec (@query) end print @query

set @query = 'insert into ' + @tableName + ' (field1) values (''test data'')' print @query set @query = 'insert into ' + @tableName + ' (field1) values (''test data'')' 打印@query

exec (@query) end exec (@query) 结束

-- exec Proc1 'order2020' -- exec Proc1 'order2020'

We can fix your SP to make it work, but I'll focus on the wrong approach I noticed you are trying to use, which is creating different versions of the same table with it's year in it's name .我们可以修复您的 SP 以使其正常工作,但我将重点关注我注意到您正在尝试使用的错误方法,即创建同一个表的不同版本,其名称中带有年份 This is a very bad design for several reasons (maintenance, performance, simplicity of querying, etc.).由于多种原因(维护、性能、查询的简单性等),这是一个非常糟糕的设计。

What you should enforce instead is to create only 1 table with a DATE (or DATETIME ) column, then query each year/month depending on your needs.您应该强制执行的是仅创建 1 个带有DATE (或DATETIME )列的表,然后根据您的需要每年/每月查询。

CREATE TABLE SaleOrder (
    SaleOrderID INT NOT NULL PRIMARY KEY,
    CustomerID   INT NOT NULL,
    CustomerName NVARCHAR(100) NOT NULL,
    CustomerNameU NVARCHAR(100) NOT NULL,
    SaleManID INT NOT NULL,
    SaleManName NVARCHAR(100) NOT NULL,
    SaleManNameU NVARCHAR(100) NOT NULL,
    SaleExecutiveID INT NOT NULL,
    SaleExecutiveName NVARCHAR(100) NOT NULL,
    SaleExecutiveNameU NVARCHAR(100) NOT NULL,
    SaleMonth INT NOT NULL,
    SaleYear  INT NOT NULL,
    SaleDate  DATE NOT NULL,
    SaleTime  TIME(2) NOT NULL,
    CreatedBy INT NOT NULL,
    CreatedName NVARCHAR(100) NOT NULL,
    CreatedNameU NVARCHAR(100) NOT NULL,
    CreatedDate DATE NOT NULL,
    UpdatedBy  INT NULL,
    UpdatedName NVARCHAR(100) NULL,
    UpdatedNameU NVARCHAR(100) NUll,
    UpdatedDate DATE NULL,

    SaleOrderDate DATE) -- We will use this new column as example

So this:所以这:

SELECT S.* FROM SaleOrder2018 AS S

becomes this:变成这样:

SELECT S.* FROM SaleOrder AS S WHERE YEAR(S.SaleOrderDate) = 2018

If when inserting you don't know which date it should be completed with, you could infer from one of your other date columns:如果在插入时您不知道应该在哪个日期完成,您可以从其他日期列之一推断:

INSERT INTO SaleOrder (
    /*All Column List*/
    SaleOrderDate)
SELECT (
    /*All Column List*/
    SaleOrderDate = @CreatedDate -- Or @UpdatedDate, or any expression you can use to know the proper date

If you might have repeated "primary keys" for SaleOrderID column amongst different years, you can use an auto-generated, no-business related value as PRIMARY KEY (which is very common to use).如果您可能在不同年份中为SaleOrderID列重复了“主键”,您可以使用自动生成的、与业务无关的值作为PRIMARY KEY (这很常见)。 You can do this declaring a column as IDENTITY :您可以这样做,将列声明为IDENTITY

CREATE TABLE SaleOrder (
    SaleOrderAutoID INT IDENTITY PRIMARY KEY,
    SaleOrderID INT NOT NULL -- remove PRIMARY KEY from this one
    /*... other columns*/
    )

Using this you don't have to check for the existence of the table before inserting, and your SP directly inserts the data without the need of Dynamic SQL:使用这个你在插入之前不必检查表的存在,你的SP直接插入数据而不需要动态SQL:

CREATE PROCEDURE SaveOrder(
    @SaleOrderID    INT,
    @CustomerID     INT,
    @CustomerName   NVARCHAR(100),
    @CustomerNameU  NVARCHAR(100),
    @SaleManID      INT,
    @SaleManName    NVARCHAR(100),
    @SaleManNameU   NVARCHAR(100),
    @SaleExecutiveID        INT,
    @SaleExecutiveName  NVARCHAR(100),
    @SaleExecutiveNameU NVARCHAR(100),
    @SaleMonth      INT,
    @SaleYear       INT,
    @SaleDate       DATE,
    @SaleTime       TIME(2),
    @CreatedBy      INT,
    @CreatedName    NVARCHAR(100),
    @CreatedNameU   NVARCHAR(100),
    @CreatedDate    DATE) 
AS
BEGIN
    INSERT INTO SaleOrder (
        SaleOrderID,
        CustomerID,
        CustomerName,
        CustomerNameU,
        SaleManID,
        SaleManName,
        SaleManNameU,
        SaleExecutiveID,
        SaleExecutiveName,
        SaleExecutiveNameU,
        SaleMonth,
        SaleYear,
        SaleDate,
        SaleTime,
        CreatedBy,
        CreatedName ,
        CreatedNameU,
        CreatedDate,
        --UpdatedBy,
        --UpdatedName,
        --UpdatedNameU,
        --UpdatedDate,
        SaleOrderDate)
    SELECT
        SaleOrderID = @SaleOrderID,
        CustomerID = @CustomerID,
        CustomerName = @CustomerName,
        CustomerNameU = @CustomerNameU,
        SaleManID = @SaleManID,
        SaleManName = @SaleManName,
        SaleManNameU = @SaleManNameU,
        SaleExecutiveID = @SaleExecutiveID,
        SaleExecutiveName = @SaleExecutiveName,
        SaleExecutiveNameU = @SaleExecutiveNameU,
        SaleMonth = @SaleMonth,
        SaleYear = @SaleYear,
        SaleDate = @SaleDate,
        SaleTime = @SaleTime,
        CreatedBy = @CreatedBy,
        CreatedName = @CreatedName,
        CreatedNameU = @CreatedNameU,
        CreatedDate = @CreatedDate,
        --UpdatedBy = ,
        --UpdatedName,
        --UpdatedNameU,
        --UpdatedDate,
        SaleOrderDate = @SaleDate

END

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以通过向后兼容的方式更改SQL Server表名吗? 例如添加一个永久别名? - Can I change a SQL Server table name in a way that is backwards compatible? E.g add a permanent alias? 如何在没有 select 语句的情况下在 SQL 服务器表中插入一些值(例如,来自我自己创建的变量) - How to insert some values in a SQL server table without select statement (e.g from my own created varibales) 如何通过值(例如-1)过滤SQL列并将表连接到另一个表 - How to filter a SQL column by a value e.g -1 and join the table to another table 如何使用返回json的存储过程调用Web服务并使用sql server将数据存储在表中? - how to Call web service using stored procedure which returns json and store data in table using sql server? 如何在 SQL 中内部连接两个表并只得到一个属性 例如,从乐队表和专辑表中获取所有有专辑的乐队 - How to inner join two tables in SQL and result to only one property E.g get all bands that have an album, from the bands table & album table SQL Server:表中的行更改了它们的顺序 - SQL Server : rows in table changed their order 如何创建一个 SQL 服务器存储过程,它可以生成一个组合三个表的表 - How can I create a SQL Server stored procedure which can produce a table combining three tables 如何在SQL Server 2014上创建用于创建表操作的存储过程? - How to create a stored procedure on SQL server 2014 for create table operation? 如何在SQL Server中的变量名上创建表? - How to Create a table on variable name in SQL Server? 将项目从一个表重新插入到另一个表的 SQL 逻辑? 例如活动记录变成非活动记录 - SQL Logic of Re-Inserting item from one table to another table? e.g Active records becoming Inactive records
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM