Generating a Database from SQL script in Visual Studio - sql-server

I was recently given a project using ASP.NET, C#, and an SQL database. I am somewhat familiar with ASP.NET and C#, however I have never used the Microsoft database software in visual studio. I simply need to generate a database from an SQL script given to me. I was able to get the database mostly generated, however some of the code (The part adding items to one of the tables) did not run on execution. I have tried adding other scripts and rerunning the first one, I cannot get anything to work. I know the script is fine, I just cant get it to run correctly. Thanks for the help. Here's the script
/*These first few lines don't run */
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Product](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](128) NOT NULL,
CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[ProductNote](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ProductID] [int] NOT NULL,
[NoteText] [nvarchar](1000) NOT NULL,
[CreateDate] [datetime] NOT NULL DEFAULT (GETDATE()),
[Archived] [BIT] NOT NULL DEFAULT (0)
CONSTRAINT [PK_ProductNote] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ProductNote] WITH CHECK ADD CONSTRAINT [FK_ProductNote_Product] FOREIGN KEY([ProductID])
REFERENCES [Product] ([ID])
GO
ALTER TABLE [dbo].[ProductNote] CHECK CONSTRAINT [FK_ProductNote_Product]
GO
/*This part does not run either */
DECLARE #n INT = 1
WHILE (#n <=20)
BEGIN
INSERT INTO dbo.Product (Name) SELECT 'Product ' + CONVERT(VARCHAR(10),#n)
SET #n = #n + 1
END
SET ANSI_PADDING OFF
GO

In Visual Studio
Go to View->Solution Explorer
Then Connect your sql Data Base
following links might be helpfull ro connect your db in visual studio
1.http://support.webecs.com/kb/a204/how-do-i-connect-to-sql-server-using-visual-studio-_net.aspx
2.https://support.zen.co.uk/kb/Knowledgebase/SQL-Server-Connecting-to-your-database-through-code-or-Visual-StudioNET
Expand your DB then Right Click on Stored Procedure -> Add new stored procedure
Replace all text with your script->Select All->Right Click ->Run Selection
That's it.

Related

Why RowVersion datatype is missing inside SSMS

We have SQL server 2017, and we want to create a new field inside existing database
the field data type is RowVersion
but using the SQL Management Studio I can not define a field with RowVersion data type
we can use Timestamps
but per my knowledge TimeStamp are now deprecated in favor of RowVersion
Any advice on this?
Here is the DataType list which does not contain rowversion:
EDIT
Now i wrote the following script to create a new table with rowversion column type:-
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[test2](
[id] [int] NOT NULL,
[rowversion] [rowversion] NOT NULL,
CONSTRAINT [PK_test2] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
but when i open the table inside the SQL management studio GUI >> the type for the new column inside the new table will be timestamp instead of rowversion + if i generate a Create to script for the new table i will get this:-
USE [test]
GO
/****** Object: Table [dbo].[test2] Script Date: 26/08/2021 19:02:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[test2](
[id] [int] NOT NULL,
[rowversion] [timestamp] NOT NULL,
CONSTRAINT [PK_test2] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
so seems rowversion can be used to create the table but it will be converted to timestamp... the issue is that Microsoft say that timestamp is deprecated and that we should use rowversion instead... totally confusing!!
This was an error in the microsoft documentation. I submitted a pull request to have that corrected, and that PR has been accepted.
The problem, and the thing confusing you here, was that the documentation claimed that "timestamp" was a synonym for "rowversion". But in fact the opposite is true. "Rowversion" is the synonym, "timestamp" is the base type name.
Both names actually refer to the same thing under the covers, but different tools have differing levels of support for synonyms. The graphical designers are old and have not been updated in a very, very long time.

Generating script from existing table having too much detail

When i use SQL Server Management Studio GUI to generate script of a table of an existing database, it produces the following:
USE [BikeStores]
GO
/****** Object: Table [production].[brands2] Script Date: 9/20/2019 3:44:27 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [production].[brands2](
[brand_id] [int] IDENTITY(1,1) NOT NULL,
[brand_name] [varchar](255) NOT NULL,
PRIMARY KEY CLUSTERED
(
[brand_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
But i want the simple table script as follows
CREATE TABLE production.brands2 (
brand_id INT IDENTITY (1, 1) PRIMARY KEY,
brand_name VARCHAR (255) NOT NULL
);
You will not be able to create the desired output in SSMS. However, you can do some slight changes in SSMS of what to output when you script your table. For example you can choose not to
Script Indexes, Triggers and Foreign keys. Etc..
Go to Tools -> Options -> Sql Server Object Explorer -> Scripting

Issue with relationship in SQL Server and Vb.net

I have a table of "CASH PAYMENT". I created two tables in SQL Server 2008 and did drag and drop in vb.net 2010.
Now when I save it with default update code, I get different errors.
I do not have any idea of relationships. I searched the web about it but did not find anything related to it. Also, what code can I use to update my relationship entry for vb.net using SQL Server?
I tried nothing - I only drag and drop the SQL Server database in vb.net and with default update code I got error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_cash-entries_cash-entries". The conflict occurred in database "dbo_main", table "dbo.cash_payn_details", column 'autonumber'
Code is shown below. This is the default code when drag drop SQL Server in vb.net
Me.Validate()
Me.Cash_payn_detailsBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Dbo_mainDataSet)
Me.Cash_entriesBindingSource.EndEdit()
Me.Cash_entriesTableAdapter.Update(Me.Dbo_mainDataSet)
I want to save two tables with one reference number. I am a beginner in vb.net and SQL Server relationships.
Edit
Table structure:
USE [dbo_main]
GO
/****** Object: Table [dbo].[cash_payn_details] Script Date: 01/04/2019 17:44:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cash_payn_details](
[autonumber] [nchar](10) NOT NULL,
[account] [nchar](10) NULL,
[amount] [nchar](10) NULL,
[date] [nchar](10) NULL,
CONSTRAINT [PK_cash_payn_details] PRIMARY KEY CLUSTERED
(
[autonumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
OTHER IS
USE [dbo_main]
GO
/****** Object: Table [dbo].[cash-entries] Script Date: 01/04/2019 17:45:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[cash-entries](
[des_autonumber] [nchar](10) NOT NULL,
[system_ID] [nchar](10) NULL,
[entries] [nvarchar](50) NULL,
CONSTRAINT [PK_cash-entries] PRIMARY KEY CLUSTERED
(
[des_autonumber] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[cash-entries] WITH CHECK ADD CONSTRAINT [FK_cash-entries_cash-entries] FOREIGN KEY([system_ID])
REFERENCES [dbo].[cash_payn_details] ([autonumber])
GO
ALTER TABLE [dbo].[cash-entries] CHECK CONSTRAINT [FK_cash-entries_cash-entries]
GO
INSERT INTO [dbo_main].[dbo].[cash-entries]
([des_autonumber]
,[system_ID]
,[entries])
VALUES
(<des_autonumber, nchar(10),>
,<system_ID, nchar(10),>
,<entries, nvarchar(50),>)
GO
other is
INSERT INTO [dbo_main].[dbo].[cash_payn_details]
([autonumber]
,[account]
,[amount]
,[date])
VALUES
(<autonumber, nchar(10),>
,<account, nchar(10),>
,<amount, nchar(10),>
,<date, nchar(10),>)
GO

Updateable view of local table and linked server table - data has changed

i need to combine two tables on a local and a linked server in a updateable view on my local sql-server, which i link to an MS Access Frontend.
Accessing this view in Access works, and updates to existing rows on the local table works to. But i can not add new rows to this local table as the foreign key [ProjektNr] is not set automatically. Sadly it is not possible to add a foreign key contraint between local and linked server, so i need an alternative. I already read about replicating/tringgering the foreign table in a local table, but this is not what i want. The two tables have a 1:1 relation. If a want to attach [Notizen] to a known Project, i need a new row in [tblProjekt] with matching [ProjektNr], but this row is not generated by updating the view. I get:
data has changed since the results pane was last retrieved
even directly in SSMS.
my local table where i can attach further projectinformation to existing projects: (SQL-Server 2014)
CREATE TABLE [dbo].[tblProjekt](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ProjektNr] [int] NOT NULL,
[Notizen] [nvarchar](max) NULL,
[TimeStamp] [timestamp] NOT NULL,
CONSTRAINT [PK_tblProjekt] PRIMARY KEY CLUSTERED
(
[ID] 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]
my linked server table which i don´t want to touch: (SQL-Server 2008R2)
CREATE TABLE [dbo].[Projekt](
[MandantNr] [smallint] NOT NULL,
[ProjektNr] [int] NOT NULL,
[KundenNr] [int] NULL,
[ProjektName] [nvarchar](150) NULL,
[Abgeschlossen] [bit] NULL,
CONSTRAINT [PK_Projekt] PRIMARY KEY NONCLUSTERED
(
[MandantNr] ASC,
[ProjektNr] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Projekt] WITH NOCHECK ADD CONSTRAINT [FK_Projekt_Mandanten] FOREIGN KEY([MandantNr])
REFERENCES [dbo].[Mandanten] ([MandantNr])
GO
ALTER TABLE [dbo].[Projekt] CHECK CONSTRAINT [FK_Projekt_Mandanten]
GO
my local combining view:
SELECT Projekt_1.ProjektNr, Projekt_1.KundenNr, Projekt_1.ProjektName,
CASE WHEN (tblProjekt.ProjektNr IS NULL) THEN '0' ELSE '-1' END AS Übernommen, dbo.tblProjekt.ID, dbo.tblProjekt.ProjektNr AS GProjektNr, dbo.tblProjekt.Notizen, dbo.tblProjekt.TimeStamp, Projekt_1.Abgeschlossen, Projekt_1.MandantNr
FROM LINKEDSERVER.Catalog.dbo.Projekt AS Projekt_1 LEFT OUTER JOIN dbo.tblProjekt ON Projekt_1.ProjektNr = dbo.tblProjekt.ProjektNr
WHERE (Projekt_1.Abgeschlossen = 0) AND (Projekt_1.MandantNr = 1)
Problem solved:
Sadly SQL-Server seems not to be able to solve this simple task.
I linked the to tables in Access, wrote the same query and it worked instantly.

Trigger Not Putting Data in History Table

I have the following trigger (along with others on similar tables) that sometimes fails to put data into the historic table. It should put data into a historic table exactly as it's inserted/updated and stamped with a date.
CREATE TRIGGER [dbo].[trig_UpdateHistoricProductCustomFields]
ON [dbo].[productCustomFields]
AFTER UPDATE,INSERT
AS
BEGIN
IF ((UPDATE(data)))
BEGIN
SET NOCOUNT ON;
DECLARE #date bigint
SET #date = datepart(yyyy,getdate())*10000000000+datepart(mm,getdate())*100000000+datepart(dd,getdate())*1000000+datepart(hh,getdate())*10000+datepart(mi,getdate())*100+datepart(ss,getdate())
INSERT INTO historicProductCustomFields (productId,customFieldNumber,data,effectiveDate) (SELECT productId,customFieldNumber,data,#date from inserted)
END
END
Schema:
CREATE TABLE [dbo].[productCustomFields](
[id] [int] IDENTITY(1,1) NOT NULL,
[productId] [int] NOT NULL,
[customFieldNumber] [int] NOT NULL,
[data] [varchar](50) NULL,
CONSTRAINT [PK_productCustomFields] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[historicProductCustomFields](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[productId] [int] NOT NULL,
[customFieldNumber] [int] NOT NULL,
[data] [varchar](50) NULL,
[effectiveDate] [bigint] NOT NULL,
CONSTRAINT [PK_historicProductCustomFields] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
I insert and update only on one record at a time on the productCustomFields table. It seems to work 99% of the time and hard to test for failure. Can anyone shed some light on what I may be doing wrong or better practices for this type of trigger?
Environment is Sql Server Express 2005. I haven't rolled out the service pack yet for sql server either for this particular client.
I think the right way to solve this is keep a TRY CATCH block when inserting into the dbo.historicProductCustomFields table and write the errors into a custom errorlog table. From there it is easy to track this down.
I also see a PK on the historicProductCustomFields table but if you insert and update a given record in ProductCustomFields table then won't you get primary key violations on the historicProductCustomFields table?
You should schema qualify your table that you are inserting into.
You should check to ensure that there are not multiple triggers on the table, as if there are, only 1 trigger for that type of trigger will fire and if there are 2 defined, they are run in random order. In other words, 2 triggers of the same type (AFTER INSERT) then one would fire and the other would not, but you don't necessary have control as to which will fire.
try to use this trigger. i just give you example try to write trigger with this trigger.
create TRIGGER [dbo].[insert_Assets_Tran]
ON [dbo].[AssetMaster]
AFTER INSERT , UPDATE
AS BEGIN
DECLARE #isnum TINYINT;
SELECT #isnum = COUNT(*) FROM inserted;
IF (#isnum = 1)
INSERT INTO AssetTransaction
select [AssetId],[Brandname],[SrNo],[Modelno],[Processor],[Ram],[Hdd],[Display],[Os],[Office],[Purchasedt]
,[Expirydt],[Vendor],[VendorAMC],[Typename],[LocationName],[Empid],[CreatedBy],[CreatedOn],[ModifiedBy]
,[ModifiedOn],[Remark],[AssetStatus],[Category],[Oylstartdt],[Oylenddt],[Configuration]
,[AStatus],[Tassign]
FROM inserted;
ELSE
RAISERROR('some fields not supplied', 16, 1)
WITH SETERROR;
END

Resources