如何在SQL Server中执行多个查询?

时间:2015-07-06 03:49:13

标签: sql-server stored-procedures

我正在尝试在表TBL_Account中插入一个帐户信息,例如现金,同时我想创建一个帐户名为Cash的表格。

ALTER PROCEDURE [dbo].[usp_AccountSaveAccount]
   @AccountId int,
   @AccountName nvarchar(Max),
   @PortalId int,
   @CultureCode nvarchar(100),
   @UserModuleId int,
   @AddedBy nvarchar(100)
AS
BEGIN
   DECLARE @SQLInsertString NVARCHAR(MAX)

   if(@AccountId = 0)
   BEGIN
      INSERT INTO dbo.AccountTable
    (
    AccountId,
    AccountName,
    PortalId,
    CultureCode,
    UserModuleId,
    AddedBy,
    AddedOn,
    UpdatedBy,
    UpdatedOn,
    IsDeleted
    )
    VALUES
    (
    @AccountId,
    @AccountName,
    @PortalId,
    @CultureCode,
    @UserModuleId,
    @AddedBy,
    GETDATE(),
    @AddedBy,
    GETDATE(),
    0
    );

    END

    DECLARE @SQLString NVARCHAR(MAX)

    SET @SQLString = 'CREATE TABLE [dbo].['+@AccountName+'](
    [AccountCatId] [int] IDENTITY(1,1) NOT NULL,
    [AccountCatName] [nvarchar](max) NULL,
    [InsertedDate] [datetime] NULL,
    [Particulars] [nvarchar](max) NULL,
    [ParticularsBy] [nvarchar](max) NULL,
    [ParticularsTo] [nvarchar](max) NULL,
    [Dr] [int] NULL,
    [Cr] [int] NULL,
    [DebitedAccountId] [int] NULL,
    [CreditedAccountId] [int] NULL,
    [DebitAmount] [float] NULL,
    [CreditAmount] [float] NULL,
    [AddedBy] [nvarchar](100) NULL,
    [AddedOn] [datetime] NULL,
    [UpdatedBy] [nvarchar](100) NULL,
    [UpdatedOn] [datetime] NULL,
    [IsDeleted] [bit] NULL,
    [DeletedBy] [nvarchar](100) NULL,
    [DeletedOn] [datetime] NULL,
 CONSTRAINT [PK_'+ @AccountName +'] PRIMARY KEY CLUSTERED 
(
    [AccountCatId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

EXEC (@SQLString)

    END

但它只创建表但不插入表中。

任何建议都将受到赞赏。

1 个答案:

答案 0 :(得分:1)

您可以在创建查询

中将nvarchar转换为varchar 像这样

SET @SQLString = 'CREATE TABLE [dbo].['+convert(varchar(200),@AccountName)+'](

CONSTRAINT [PK_'+ convert(varchar(200),@AccountName) +'] PRIMARY KEY CLUSTERED