Can you help me fix the error
There is already an object name in database
My code:
CREATE DATABASE DIEMTHAMQUAN
USE DIEMTHAMQUAN
CREATE TABLE QUOCGIA
(
MAQG NCHAR(5) NOT NULL,
TENQG NCHAR(20) NULL,
TD NCHAR(5) NOT NULL,
DS INT NULL,
DT REAL NULL
CONSTRAINT PK_QUOCGIA PRIMARY KEY(MAQG,TD)
)
CREATE TABLE TINHTHANH
(
MATT NCHAR(5) NOT NULL,
QG NCHAR(5) NULL,
DS INT NULL,
DT REAL NULL,
TENTT NCHAR(30) NULL
CONSTRAINT PK_TINHTHANH PRIMARY KEY(MATT)
)
CREATE TABLE DIEMTHAMQUAN
(
MADTQ NCHAR(10) NOT NULL,
TENDTQ NCHAR(30) NULL,
TT NCHAR(5) NULL,
QG NCHAR(5) NULL,
DD NCHAR(50) NULL
CONSTRAINT PK_DIEMTHAMQUAN PRIMARY KEY(MADTQ)
)
ALTER TABLE TINHTHANH
ADD CONSTRAINT FK_TT_QG FOREIGN KEY(QG) REFERENCES QUOCGIA(MAQG)
ALTER TABLE DIEMTHAMQUAN
ADD CONSTRAINT FK_DTQ_TT FOREIGN KEY(TT) REFERENCES TINHTHANH(MATT)
--insert QUOCGIA(MAQG,TENQG,TD,DS,DT)
INSERT INTO QUOCGIA(MAQG, TENQG, TD, DS, DT)
VALUES (N'QG001', N'VIỆT NAM', N'TT001', CAST(N'115000000' AS INT), CAST(N'331688.00' AS REAL)),
(N'QG002', N'NHẬT BẢN', N'TT003', CAST(N'129500000' AS INT), CAST(N'337834.00' AS REAL))
--insert TINHTHANH(QG,MATT,TENTT,DS,DT)
INSERT INTO TINHTHANH(QG, MATT, TENTT, DS, DT)
VALUES (N'QG001', N'TT001', N'HÀ NỘI', CAST(N'2500000' AS INT), CAST(N'927.39' AS REAL)),
(N'QG001', N'TT002', N'HUẾ', CAST(N'5344000' AS INT), CAST(N'5009.00' AS REAL)),
(N'QG002', N'TT003', N'TOKYO', CAST(N'12084000' AS INT), CAST(N'2187.00' AS REAL))
The problem lies here:
CREATE TABLE DIEMTHAMQUAN
You are using the same name for the ‘Database’ and guving the same name to a ‘table’. If in future you call this ‘DIEMTHAMQUAN’ how would Sql-Server(if you are using this) know that you are referring to database or table.
Possible solution is to name your table ‘tblDIEMTHAMQUAN’.
Related
I am getting an error
Incorrect syntax near ','
and do not know how to fix it.
I have tried rewriting the query, referencing old code, and nothing seems to work.
USE RewriteExam
GO
IF EXISTS(SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID('dbo.Vendors')
AND type IN ('U'))
BEGIN
PRINT 'Vendors table already exists, dropping it now!'
DROP TABLE Vendors
END
GO
PRINT 'Creating the "Vendors" Table'
CREATE TABLE dbo.Vendors
(
VendorID INT PRIMARY KEY,
VendorName VARCHAR(45) NOT NULL,
VendorAddress VARCHAR(45) NULL,
VendorCity VARCHAR(45) NOT NULL,
VendorState VARCHAR(45) NOT NULL,
VendorZipCode VARCHAR(45) NOT NULL,
VendorPhone VARCHAR(45) NULL,
VendorContactLName VARCHAR(7) NULL,
VendorContactFName VARCHAR(14) NULL,
AcountNo INT NOT NULL,
ModifiedDate SMALLDATETIME NOT NULL,
AccountNo INT FOREIGN KEY,
CONSTRAINT PK_Vendors_VendorID
PRIMARY KEY (VendorID)
--REFERENCES Vendors (VendorID)
);
GO
PRINT 'Creating the "GLAccounts" Table'
CREATE TABLE dbo.GLAccounts
(
AccountNo INT PRIMARY KEY,
AccountDescription VARCHAR(45) NOT NULL,
);
GO
The trouble is in the constraints. The comma after the foreign key is giving me the error as well as PRIMARY KEY (VendorID)
Just need to add the commented out part after
AccountNo INT FOREIGN KEY
and convert to
AccountNo INT FOREIGN KEY REFERENCES Vendors (VendorID)
and remove already defined constraint PRIMARY KEY (VendorID)
I have written the following stored procedure to return data based on a lat/long and category id being passed.
I need to return a list of traders whose coverage area falls within the passed lat long (and that they cover the category being passed). So I am looking to draw a circle around the traders lat/long position, x number of meters using the radius they will operate from (this is stored in the Traders.OperatingRadius column). If the passed lat long coord is within this, then they should be included in the return list.
CREATE PROCEDURE FindTradersWithinRadiusLatLong
#LAT decimal(9,6),
#LONG decimal(9,6),
#CATEGORY int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #GEO1 GEOGRAPHY;
SET #GEO1 = geography::Point(#LAT, #LONG, 4326)
SELECT
x.Id, x.Name,
x.Latitude, x.Longitude,
x.Distance, x.IsArchived
FROM
(SELECT
Traders.Id, Traders.Name,
Latitude, Longitude,
CategoryId = TraderCategories.Id,
OperatingRadius,
Traders.IsArchived,
Distance = (#geo1.STDistance(geography::Point(ISNULL(Latitude, 0), ISNULL(Longitude, 0), 4326)))
FROM
((Addresses
INNER JOIN
Traders ON Addresses.TraderId = Traders.Id)
INNER JOIN
TraderCategories ON Traders.Id = TraderCategories.TraderId)) AS x
WHERE
x.Distance <= x.OperatingRadius
AND x.CategoryId = #CATEGORY
AND (x.IsArchived = 0 OR x.IsArchived = NULL);
END
GO
TraderCategories is a linking table as follows;
Table TraderCategories
int FK TraderId
int FK CategoryId
Now I have added an address with;
latitiude - 43.590000, Longitude - -111.120000
There is also a TraderCategory Relationship for category with Id 1
I have then tried calling the stored procedure with the above and no matches are being returned.
The table definitions are as follows:
CREATE TABLE [Bemfeito].[Addresses]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Address1] [nvarchar](max) NULL,
[Address2] [nvarchar](max) NULL,
[Address3] [nvarchar](max) NULL,
[TraderId] [int] NULL,
[Latitude] [decimal](9, 6) NOT NULL,
[Longitude] [decimal](9, 6) NOT NULL,
[OperatingRadius] [real] NOT NULL DEFAULT (CONVERT([real],(0)))
CONSTRAINT [PK_Addresses]
PRIMARY KEY CLUSTERED ([Id] ASC)
)
GO
ALTER TABLE [Bemfeito].[Addresses] WITH CHECK
ADD CONSTRAINT [FK_Addresses_Traders_TraderId]
FOREIGN KEY([TraderId]) REFERENCES [Bemfeito].[Traders] ([Id])
GO
ALTER TABLE [Bemfeito].[Addresses] CHECK CONSTRAINT [FK_Addresses_Traders_TraderId]
GO
CREATE TABLE [Bemfeito].[Traders]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Email] [nvarchar](max) NULL
[Name] [nvarchar](max) NULL
CONSTRAINT [PK_Traders]
PRIMARY KEY CLUSTERED ([Id] ASC)
)
GO
CREATE TABLE [Bemfeito].[TraderCategories]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[CategoryId] [int] NULL,
[TraderId] [int] NULL,
CONSTRAINT [PK_TraderCategories]
PRIMARY KEY CLUSTERED ([Id] ASC)
)
GO
ALTER TABLE [Bemfeito].[TraderCategories] WITH CHECK
ADD CONSTRAINT [FK_TraderCategories_Categories_CategoryId]
FOREIGN KEY([CategoryId]) REFERENCES [Bemfeito].[Categories] ([Id])
GO
ALTER TABLE [Bemfeito].[TraderCategories] CHECK CONSTRAINT [FK_TraderCategories_Categories_CategoryId]
GO
ALTER TABLE [Bemfeito].[TraderCategories] WITH CHECK
ADD CONSTRAINT [FK_TraderCategories_Traders_TraderId]
FOREIGN KEY([TraderId]) REFERENCES [Bemfeito].[Traders] ([Id])
GO
ALTER TABLE [Bemfeito].[TraderCategories] CHECK CONSTRAINT [FK_TraderCategories_Traders_TraderId]
GO
and finally for completion the category
CREATE TABLE [Bemfeito].[Categories]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[Value] [int] NOT NULL,
CONSTRAINT [PK_Categories]
PRIMARY KEY CLUSTERED ([Id] ASC)
)
Can anyone tell me where I am going wrong here please?
If you look at this microsoft reference here you should notice that the argument passed to STDistance is a geometry datatype while you are passing a Point datatype.
the line currently written like this
,Distance = (#geo1.STDistance(geography::Point(ISNULL(Latitude, 0), ISNULL(Longitude, 0), 4326))
should be written as follows.
,Distance = (#geo1.STDistance(geography::STGeomFromText('Point('+ISNULL(Longitude, 0)+' '+ISNULL(Latitude, 0)')',4326))
Im running stored procedure which in charges to insert, update and delete table's entries.
While both insert and delete runs smoothly, the update operation updates all columns except DATETIME2 one.
The scenario - I test my Repository pattern (using C# code) in the following way:
delete the entire [BackgroundTaskAttachtment] table
Create 4 new entries
delete single entry created on step 2
Wait for 5 seconds
modify one of the entries
the result is having 3 entries in [BackgroundTaskAttachtment] table, with all properties set as expected, except the [UpdatedOnUtc] which not updated (it is equal to [CreatedOnUtc]
I marked the updated row (as you can see [FilePath] was successfully updated):
Would appreciate community insights,
Thank you
This is the stored procedure code:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_ArrangeBackgroundTaskAttachtments]
(
#backgroundTaskId BIGINT,
#taskAttchs [dbo].[BackgroundTaskAttachtmentType] READONLY
)
AS
BEGIN
SET NOCOUNT ON;
--delete all removed attachtments
DELETE FROM [BackgroundTaskAttachtment]
WHERE [BackgroundTaskId] = #backgroundTaskId AND [Id] NOT IN (SELECT [Id] FROM #taskAttchs)
----Update exist key-value pairs
UPDATE [dbo].[BackgroundTaskAttachtment]
SET
[IsPrimary] = attachs.[IsPrimary],
[FilePath] = attachs.[FilePath],
[Bytes] = attachs.[Bytes],
[UpdatedOnUtc] = GETUTCDATE()
FROM #taskAttchs AS attachs
WHERE attachs.[Id] = [BackgroundTaskAttachtment].[Id]
--insert new records
SELECT #backgroundTaskId AS [BackgroundTaskId], [FilePath], [IsPrimary], [Bytes], GETUTCDATE() AS [CreatedOnUtc], GETUTCDATE() AS [UpdatedOnUtc]
INTO #Temp FROM #taskAttchs as atcs
WHERE atcs.[Id] NOT IN (SELECT [Id] FROM [BackgroundTaskAttachtment] AS bta WHERE bta.[BackgroundTaskId] = #backgroundTaskId )
INSERT INTO [BackgroundTaskAttachtment]([BackgroundTaskId], [IsPrimary], [Bytes], [FilePath], [CreatedOnUtc], [UpdatedOnUtc] )
SELECT [BackgroundTaskId], [IsPrimary], [Bytes], [FilePath], [CreatedOnUtc], [UpdatedOnUtc]
FROM #Temp
END
This is the table type (sent from CLR to SQL)
CREATE TYPE [dbo].[BackgroundTaskAttachtmentType] AS TABLE(
[Id] [BIGINT] NOT NULL,
[FilePath] [NVARCHAR](MAX) NULL,
[IsPrimary] [BIT] NOT NULL,
[BackgroundTaskId] [BIGINT] NULL,
[Bytes] [VARBINARY](MAX) NULL
)
GO
this is the table definition
CREATE TABLE [dbo].[BackgroundTaskAttachtment]
(
[Id] BIGINT IDENTITY(1,1) NOT NULL,
[BackgroundTaskId] BIGINT NOT NULL,
[IsPrimary] BIT NOT NULL DEFAULT 0,
[FilePath] NVARCHAR(MAX) NULL,
[Bytes] VARBINARY(MAX) NULL,
[CreatedOnUtc] DATETIME2 NOT NULL,
[UpdatedOnUtc] DATETIME2 NOT NULL,
[RowVersion] ROWVERSION NOT NULL,
CONSTRAINT [PK_dbo.BackgroundTaskAttachtment] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.BackgroundTaskAttachtment_BackgroundTask_Id]
FOREIGN KEY ([BackgroundTaskId])
REFERENCES [dbo].[BackgroundTask] ([Id])
ON DELETE CASCADE
);
Please try using SYSUTCDATETIME which returns datetime2.
The GETUTCDATE which you are using, returns datetime.
Please help me figure out how to Insert new record with composite primary key, which consists of two foreign keys from different tables.
I am working in C#, WPF if that matters.
I have three tables: Sales, SaleItem, Item.
CREATE TABLE [dbo].[Sales] (
[saleID] INT IDENTITY (1, 1) NOT NULL,
[saleTime] DATETIME NOT NULL,
[customerID] INT NULL,
[TIN] INT NOT NULL,
CONSTRAINT [PK_Sales] PRIMARY KEY CLUSTERED ([saleID] ASC),
CONSTRAINT [FK_Sales_Customers] FOREIGN KEY ([customerID]) REFERENCES [dbo].[Customers] ([customerID]),
CONSTRAINT [FK_Sales_Company] FOREIGN KEY ([TIN]) REFERENCES [dbo].[Company] ([TIN])
);
CREATE TABLE [dbo].[Item] (
[ItemSKU] INT IDENTITY (1, 1) NOT NULL,
[itemName] NVARCHAR (50) NOT NULL,
[volume] FLOAT (53) NOT NULL,
[measureUnit] NVARCHAR (50) NOT NULL,
[producer] NVARCHAR (50) NOT NULL,
[supplierID] INT NOT NULL,
[retailPrice] NUMERIC (18) NOT NULL,
CONSTRAINT [PK_Item] PRIMARY KEY CLUSTERED ([ItemSKU] ASC),
CONSTRAINT [FK_Item_Suppliers] FOREIGN KEY ([supplierID]) REFERENCES [dbo].[Suppliers] ([supplierID])
);
CREATE TABLE [dbo].[SaleItem] (
[saleID] INT IDENTITY (1, 1) NOT NULL,
[itemSKU] INT NOT NULL,
[quantity] INT NOT NULL,
CONSTRAINT [PK_SaleItem] PRIMARY KEY CLUSTERED ([saleID] ASC, [itemSKU] ASC),
CONSTRAINT [FK_SaleItem_Sales] FOREIGN KEY ([saleID]) REFERENCES [dbo].[Sales] ([saleID]),
CONSTRAINT [FK_SaleItem_Item] FOREIGN KEY ([itemSKU]) REFERENCES [dbo].[Item] ([ItemSKU])
);
I want to insert a new record into SaleItem table (the third one) where saleID is the last ID recorded in Sales table and ItemSKU which is equal to the value I get from another window.
I want these values:
SaleID = SELECT TOP 1 saleID FROM Sales ORDER BY saleID DESC";
ItemSKU = "SELECT itemName FROM Item WHERE ItemSKU = #sku";
I think I must do it in one query but I have no idea how.
Can you please give me a hint? I
First, you need to remove the IDENTITY property from the dbo.SaleItem table. The IDENTITY property is only required on the parent table, dbo.Sales.
You can do a single INSERT statement like this. It uses two subqueries, which are the SELECT statements in parentheses, to get values from the other two tables.
INSERT INTO dbo.SaleItem (saleID, itemSKU, quantity)
VALUES ((SELECT MAX(saleID) FROM dbo.Sales),
(SELECT ItemSKU FROM dbo.Item WHERE itemName = N'Widget'),
50);
You might want to turn it into a stored procedure, like this:
CREATE PROCEDURE dbo.up_InsertSaleItem
(
#itemName nvarchar(50),
#quantity int
)
AS
INSERT INTO dbo.SaleItem (saleID, itemSKU, quantity)
VALUES ((SELECT MAX(saleID) FROM dbo.Sales),
(SELECT ItemSKU FROM dbo.Item WHERE itemName = #itemName),
#quantity);
Then to use the stored procedure:
-- Test the stored procedure
EXEC dbo.up_InsertSaleItem #itemName=N'Widget', #quantity=50;
SELECT *
FROM dbo.SaleItem;
To read more about subqueries, see Microsoft SQL Server 2012 T-SQL Fundamentals by Itzik Ben-Gan, Chapter 4: Subqueries.
maybe I can get some feedback from some folks on this. I created two tables and inserted data into one table and i put a constraint (Foreign key) on the table std_individual_address.
I get the following error message when I try to execute the insert now:
Msg 515, Level 16, State 2, Line 43 Cannot insert the value NULL into
column 'individual_GUID', table 'ABLE.dbo.std_individual_address';
column does not allow nulls. INSERT fails. The statement has been
terminated.
Here is all my code:
--Create the std_individual table
CREATE TABLE std_individual(
individual_GUID INT NOT NULL IDENTITY,
individual_First_Name VARCHAR(50) NULL,
individual_Last_Name VARCHAR(50) NULL,
individual_email VARCHAR(40) NULL,
PRIMARY KEY (individual_GUID));
--Create the std_individual_address table
CREATE TABLE std_individual_address
(
individual_address_GUID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
individual_address_line1 VARCHAR(100) NULL,
individual_address_line2 VARCHAR(100) NULL,
individual_address_line3 VARCHAR(100) NULL,
individual_address_city VARCHAR(50) NULL,
individual_address_state VARCHAR(30) NULL,
individual_address_zipcode VARCHAR(30) NULL,
individual_GUID INT NOT NULL,
CONSTRAINT fk_std_individual_address_std_individual FOREIGN KEY (individual_GUID) REFERENCES std_individual (individual_GUID)
)
--Insert Individual Data
INSERT INTO std_individual
(individual_First_Name,individual_Last_Name,individual_email)
VALUES
('Terry','Smith','tsmith#example.net'),
('Ronald','Smegan','ronald#example.net'),
('Arnold','Aggassi','aaggassi#example.edu'),
('Jerry','Brukheimer','bbrukheimer#example.edu');
--Mind the Constraint
INSERT INTO std_individual_address(individual_GUID) SELECT individual_GUID from std_individual
--Attempt to insert rest of the data
INSERT INTO std_individual_address
(individual_address_line1,individual_address_line2,individual_address_city,individual_address_state,
individual_address_zipcode )
VALUES
('8200 Greensboro Drive','Ste 1500','Mclean','Virgina','22102'),
('1121 14th Street, NW','Ste 1000','Washington' ,'District of Columbia','20005'),
('1700 Connecticut Ave,NW','Ste 300','Washington' ,'District of Columbia','20009'),
('205 Pennsylvania Ave,SE','','Washington','District of Columbia','20003');
Then I get the error message above. Any ideas on how to combat that issue?