Subqueries are not allowed in this context. Only scalar expressions are allowed in CREATE TABLE with AS syntax - sql

I am trying to run the below script but I keep getting the error messages
"Subqueries are not allowed in this context. Only scalar expressions are allowed." on lines 16 and 34.
I know where it's failing - it is failing on the AS clauses, but I don't know how to correct it with different code to stop the errors from appearing.
I have tried looking around at other existing questions but none helped me that I can find. As the issue I have here is using data from columns in different tables along with columns in the current table.
Could I get some help with getting this working and advise what code will be better please?
Thanks for your help in advance!
Dan
This is the code for my database::
CREATE DATABASE [LEARNING]
GO
CREATE TABLE Trainees
(
Trainee_ID int IDENTITY(1,1) PRIMARY KEY NOT NULL,
Name varchar(50) NOT NULL,
[Assigned Tutor_ID] int NOT NULL,
)
GO
CREATE TABLE Tutors
(
Tutor_ID int IDENTITY(1,1) PRIMARY KEY NOT NULL,
Name varchar(50) NOT NULL,
[Assigned Trainee_ID] AS (Select Trainee_ID from Trainees where Tutors.[Assigned Trainee_ID] = Trainees.Trainee_ID) NOT NULL
)
GO
CREATE TABLE [Rooms]
(
Room_ID int IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Room Name] varchar(50) NOT NULL,
[Cost per hour] money NOT NULL
)
GO
CREATE TABLE [Rooms Rented]
(
Rented_ID int IDENTITY(1,1) PRIMARY KEY NOT NULL,
Room_ID int NOT NULL,
Tutor_ID int NOT NULL,
[Length of time in hours] int NOT NULL,
[Total Cost] AS (select ([Rooms Rented].[Length of time in hours])*([Rooms].[Cost per hour]) from [Rooms]) NOT NULL
)
GO
INSERT INTO Tutors values ('Nikki Smith',1)
GO
INSERT INTO Trainees Values ('Tyler Hatherall')
GO
INSERT INTO Rooms values ('Training Room 1',6.50)
GO
INSERT INTO [Rooms Rented] values (1,1,2)
GO

Computed columns are used to ensure columns persisted property within the table itself.
In your case, you need to have another update after you created table, populate the column by the query similar to below query, also, you need to create Foreign Key in the Total Cost column based on what you try to achieve.
UPDATE A
SET A.[Total Cost] = A.[Length of time in hours] * B.[Cost per hour] --add ISNULL to treat NULL if needed
FROM [Rooms Rented] as A
INNER JOIN [Rooms] as B
ON B.Room_ID = A.Room_ID

Your AS statements are computed columns. When your computed columns refer to other tables, you cannot implement this directly. You will have to create scalar functions first.
For example, after creating Rooms, create this function that takes a room id and returns cost per hour:
create function f_get_Rooms_CostPerHour (#Room_ID int)
returns money
as
return (select [Cost per hour] from [Rooms] where [Rooms].Room_ID=#Room_ID)
Now you can use this in your computed column formula. Note that a computed column formula never has a SELECT in it. It also does not have a null/not null specification.
CREATE TABLE [Rooms Rented]
(
Rented_ID int IDENTITY(1,1) PRIMARY KEY NOT NULL,
Room_ID int NOT NULL,
Tutor_ID int NOT NULL,
[Length of time in hours] int NOT NULL,
[Total Cost] AS ([Length of time in hours]*f_get_Rooms_CostPerHour([Room_ID]))
)

Related

How do I insert a subquery with multiple results into multiple rows?

I want to add the results of a query into a table. There are multiple values, being inserted into multiple rows that are currently NULLS.
I have the following tables:
CREATE TABLE CAR (
CarID INT NOT NULL PRIMARY KEY,
Make VARCHAR (30) NOT NULL,
Model VARCHAR (30) NOT NULL,
Type VARCHAR (30) NOT NULL,
YearModel INT NOT NULL,
Price VARCHAR (100) NOT NULL,
);
CREATE TABLE [TRANSACTION] (
tID INT NOT NULL PRIMARY KEY,
cID INT NOT NULL FOREIGN KEY REFERENCES CUSTOMER(CID),
CarID INT NOT NULL FOREIGN KEY REFERENCES CAR(CARID),
eID INT NOT NULL FOREIGN KEY REFERENCES EMPLOYEE(EID),
tDate DATE,
PickupDate DATE NOT NULL,
ReturnDate DATE NOT NULL
);
I then had to add a new column:
ALTER TABLE [TRANSACTION]
ADD Amount_Due int;
The following code gives me the results I need:
SELECT Price*DATEDIFF(DAY,PickupDate, ReturnDate)
FROM [TRANSACTION], CAR
WHERE [TRANSACTION].CarID = CAR.CarID
But I don't know how to insert all of the data into my Amount_Due column.
I have tried to use INSERT INTO, but it's telling me I have a syntax error near Amount_Due.
INSERT INTO [TRANSACTION] Amount_Due
SELECT Price*DATEDIFF(DAY,PickupDate, ReturnDate)
FROM CAR, [TRANSACTION]
WHERE CAR.CarID = [TRANSACTION].CarID
I have played around with INSERT INTO and UPDATE and I cannot wrap my head around what I'm doing wrong, or what I am missing.
I'm using SQL SMS 2018
Thank you for any help.
You are not inserting data you are updating existing rows, so you need to update:
update t set
t.Amount_Due = c.Price * DateDiff(day, c.PickupDate, c.ReturnDate)
from [transaction] t
join car c on c.carId=t.carId
Notes
Always use proper join syntax, avoid adding tables separated by
commas.
Also always alias your tables with meaningful short
aliases for readability.
Avoid using reserved words for objects eg
transaction - if your table contains more than 1 row then call it
transactions and avoid the need to always have to use [] to avoid
ambiguity.
SSMS is not SQL Server, SSMS is just an application used to access SQL Server. Use select ##version if you ever need to know your SQL Server version.

Computed column at creation of table gets evaluated every time

I have the following script that creates a table:
CREATE TABLE [dbo].[Persons]
(
[Id] INT IDENTITY(1,1) NOT NULL,
[Name] NVARCHAR(250) NOT NULL,
[Surname] NVARCHAR(250) NOT NULL,
[NumberOfNotes] INT NOT NULL,
[TotalCash] FLOAT NOT NULL,
[Result] AS ([NumberOfNotes] * [TotalCash] * ROUND(RAND() * 2, 0)),
CONSTRAINT [PK_Persons] PRIMARY KEY ([Id] ASC)
);
The table gets created correctly and whenever I insert a new person the Result gets calculated. Problem is that it gets re-evaluated every time I do a select. I would like the computed value to stay the same for that record. How do I achieve this? Thanks in advance!
I simple trick is to seed rand():
[Result] AS ([NumberOfNotes] * [TotalCash] * ROUND(RAND(id) * 2, 0)),
Basically, this is using a "deterministic" random number generator. You can do that in other ways as well.
Alternatively, you could just assign it a value when you insert new rows into the table.

T-SQL create table statement will not accept variable

Why can I not use a variable to name a new table?
As a beginning SQL project, I'm making a personal finance database. Each account will have a corresponding table in the database. There is also a table listing all the current accounts. See (simplified) code sample below:
CREATE TABLE accountList
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[Name] NCHAR(30) NOT NULL UNIQUE,
[Active] BIT NOT NULL
)
INSERT INTO accountList(name, active)
VALUES
('Bank_One_Checking', 1);
CREATE TABLE Bank_One_Checking
(
[Id] BIGINT NOT NULL PRIMARY KEY IDENTITY,
[payee] NCHAR(30) NOT NULL UNIQUE,
[category] NCHAR(30) NOT NULL UNIQUE,
[amount] INT NOT NULL DEFAULT 0.00
)
This code works. I want to set the account name to a variable (so it can be passed as a parameter to a stored procedure). See code below:
DECLARE #accountName nchar(30);
SET #accountName = 'Bank_One_Savings';
INSERT INTO accountList(name, active)
VALUES
(#accountName, 1);
CREATE TABLE #accountName
(
[Id] BIGINT NOT NULL PRIMARY KEY IDENTITY,
[payee] NCHAR(30) NOT NULL UNIQUE,
[category] NCHAR(30) NOT NULL UNIQUE,
[amount] INT NOT NULL DEFAULT 0.00
)
Line 6 in that code (CREATE TABLE #accountName) produces an error
Incorrect syntax near #accountName, expecting '.', 'ID', or 'QUOTEID'.
Why won't it insert the variable into the command?
SQL doesn't allow tables to be variables. You could use dynamic SQL, if you like, but I strongly recommend against it.
Your code has several flaws. You should learn not only to fix them but why they are wrong.
You need a "master" table, where AccountName is a column. Multiple tables with the same structure is almost always a sign of poor database design.
Strings should be designed using VARCHAR() or NVARCHAR(), unless they are short or known to be the same length (say an account number that is always 15 characters). Fixed-length strings just waste space.
I find it unlikely that a column named category would be unique in such a table. It seems to violate what uniqueness means.
Integers are not appropriate for monetary amounts in most of the world (use decimal or money). And, they shouldn't be initialized to constants with a decimal point.

Table cell to count rows in other table

I'm not entirely sure if I'm even going about this in the right manner.
MVC+EF site so i could do this in the controller but I would prefer it in the DB if possible.
I have two tables. One contains entries and one contains a list of members. I want the list of members to have a column that contains the count of how many times the member name appears in the list of entries. Can I do this in the definition of the table itself?
I know this query works:
select count(*)
from dbo.Entries
where dbo.Entries.AssignedTo = 'Bob Smith'
But is there any way of doing this? What is the correct syntax?
CREATE TABLE [dbo].[Members] (
[ID] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (100) NOT NULL,
[Email] NVARCHAR (500) NOT NULL,
[Count] INT = select count(*) from dbo.Entries where dbo.Entries.AssignedTo = [Name]
PRIMARY KEY CLUSTERED ([ID] ASC)
I've done some searching and have tried a few different syntax's but I'm completely lost at this point so if anyone can get me headed in the correct direction I would really appreciate it.
Thanks in advance.
You could create Members as a view combining both the Entries data and another table. (Warning: Syntax not tested)
CREATE TABLE [_member_data] (
[ID] INT IDENTITY(1, 1) NOT NULL,
[Name] NVARCHAR (100) NOT NULL,
[Email] NVARCHAR (500) NOT NULL,
PRIMARY KEY CLUSTERED ([ID] ASC)
);
CREATE VIEW [dbo].[Members] AS
SELECT ID, Name, Email, COUNT(*)
FROM _member_data JOIN dbo.Entries ON [Name] = [AssignedTo]
GROUP BY 1, 2, 3;
It is possible to take this even further with triggers/rules that rewrite attempted inserts into Members as inserts to the appropriate backing table. But to get the kind of expressive information that you are looking for, you really want to explore using a view.

How to update 2nd table with identity value of inserted rows into 1st table

I have the following table structures
CREATE TABLE [dbo].[WorkItem](
[WorkItemId] [int] IDENTITY(1,1) NOT NULL,
[WorkItemTypeId] [int] NOT NULL,
[ActionDate] [datetime] NOT NULL,
[WorkItemStatusId] [int] NOT NULL,
[ClosedDate] [datetime] NULL,
)
CREATE TABLE [dbo].[RequirementWorkItem](
[WorkItemId] [int] NOT NULL,
[RequirementId] [int] NOT NULL,
)
CREATE TABLE #RequirmentWorkItems
(
RequirementId int,
WorkItemTypeId int,
WorkItemStatusId int,
ActionDate datetime
)
I use the #RequirmentWorkItems table to create workitems for requirements. I then need to INSERT the workitems into the WorkItem table and use the identity values from the WorkItem table to create the cross-reference rows in the RequirementWorkItem table.
Is there a way to do this without cursoring thru each row? And I can't put the RequirementId into the WorkItem table because depending on the WorkItemTypeId the WorkItem could be linked to a Requirement or a Notice or an Event.
So there are really 3 xref tables for WorkItems. Or would it be better to put a RequirementId, NoticeId and EventId in the WorkItem table and 1 of the columns would have a value and other 2 would be null? Hopefully all this makes sense. Thanks.
You should read MERGE and OUTPUT – the swiss army knife of T-SQL for more information about this.
Today I stumbled upon a different use for it, returning values using an OUTPUT clause from a table used as the source of data for an insertion. In other words, if I’m inserting from [tableA] into [tableB] then I may want some values from [tableA] after the fact, particularly if [tableB] has an identity. Observe my first attempt using a straight insertion where I am trying to get a field from #source.[id] that is not used in the insertion: