I have just started learning SQL and I'm really struggling. I have a very simple employees table and trying to link it with a leave table.
CREATE TABLE [MOUNTAIN].[VOLUNTEER]
(
[EMPLOYEE_ID] [int] identity (1,1) not null,
[NAME] [nvarchar] (20) not null,
[PHONENUMBER] [nvarchar] (20) not null,
[ADDRESS] [NVARCHAR] (200) NOT NULL
);
CREATE TBALE [EMPLOYEE_LEAVE]
(
[LEAVE_ID] [int] identity (1,1) not null,
[EMPLOYEE_ID] [int] not null,
[START_DATE] [DATE] not null,
[END_DATE] [DATE] not null,
);
I want these to be linked so an employee can enter start date and end date and submit it online and it will update in SQL Server.
I'm sure this is very simple and i have been searching for hours trying to find a solution.
Related
Is there someone who can help me figure out why I cannot query an external table that I created using my SQL Server Mgt Studio. I can see the external table if I expand External Tables but if I Right click and Select Top 1000 Rows I get an error that Invalid object name 'dbo.AuditLogSource'.
I am trying to copy a certain amount of data from an audit log table in DB1.AuditLog into ArchiveDB.AuditLog. I've followed the tutorials on how to use Elastic Queries to archive this simple task but I am now stuck at this point where I should query from the external table created locally in my ArchiveDB. Here's the process I followed maybe I made a mistake somewhere please help me:
CREATE MASTER KEY ENCRYPTION BY PASSWORD = '2019MoxvE!';
--DROP MASTER KEY;
CREATE DATABASE SCOPED CREDENTIAL SQL_Credential
WITH IDENTITY = 'myusername',
SECRET = '2019MoxvE!';
--DROP DATABASE SCOPED CREDENTIAL SQL_Credential;
CREATE EXTERNAL DATA SOURCE RemoteReferenceData
WITH
(
TYPE=RDBMS,
LOCATION='ourserver.database.windows.net',
DATABASE_NAME='DB1',
CREDENTIAL= SQL_Credential
);
--DROP EXTERNAL DATA SOURCE RemoteReferenceData;
CREATE EXTERNAL TABLE [dbo].[AuditLogSource]
(
[Id] [int] NOT NULL,
[Userid] [int] NOT NULL,
[ObjectId] [int] NULL,
[CreatedOn] [datetime] NOT NULL,
[ModifiedOn] [datetime] NOT NULL,
[ModifiedBy] [varchar](150) NOT NULL,
[Type] [int] NOT NULL,
[ActionTable] [varchar](50) NOT NULL,
[IsAjaxRequest] [bit] NOT NULL,
[Parameters] [varchar](max) NOT NULL,
[Controller] [varchar](50) NOT NULL,
[Action] [varchar](50) NOT NULL,
[Comments] [varchar](max) NULL,
[BeforeImage] [varchar](max) NULL,
[AfterImage] [varchar](max) NULL,
[Browser] [varchar](max) NULL
)
WITH (DATA_SOURCE = [RemoteReferenceData]);
--DROP EXTERNAL TABLE [dbo].[AuditLogSource];
INSERT INTO [dbo].[AuditLog]
SELECT al.* FROM [dbo].[AuditLogSource] al WHERE al.[CreatedOn] <= '2020/12/31' AND
NOT EXISTS(SELECT 1 FROM [dbo].[AuditLog] al1 WHERE al1.Id=al.Id);
If you see on below screenshot, you can see that there are no errors being highlighted on this query which means that the query window does recognise that the table AuditLogSource does exists but if I run the query it complains that it does not exists. I can also confirm that the user I am logged into the database with is the admin user and own of both DB1 and ArchiveDB What can I do to make this work?
Thanks in advance.
Make sure you're using the correct database also if you create a new SQL Server object, your newly created object does not get updated in the IntelliSense Local Cache and due to this, it shows an Invalid object name: dbo.AuditLogSource.Please follow below reference.
Ex: [DatabaseName].[Schema].[TableName]
Try:
Edit -> IntelliSense -> Refresh Local Cache or Ctrl + shift + R
Reference:
Sql server invalid object name - but tables are listed in SSMS tables list
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-external-table-transact-sql?view=sql-server-ver16&tabs=dedicated
Ok so I will post an answer to this question in case another person comes across the same/similar problem. So I only made 1 mistake in creating the External Table and this is because of the tutorials and other answers I saw on this very platform.
CREATE EXTERNAL TABLE [dbo].[AuditLogSource]
(
[Id] [int] NOT NULL,
[Userid] [int] NOT NULL,
[ObjectId] [int] NULL,
[CreatedOn] [datetime] NOT NULL,
[ModifiedOn] [datetime] NOT NULL,
[ModifiedBy] [varchar](150) NOT NULL,
[Type] [int] NOT NULL,
[ActionTable] [varchar](50) NOT NULL,
[IsAjaxRequest] [bit] NOT NULL,
[Parameters] [varchar](max) NOT NULL,
[Controller] [varchar](50) NOT NULL,
[Action] [varchar](50) NOT NULL,
[Comments] [varchar](max) NULL,
[BeforeImage] [varchar](max) NULL,
[AfterImage] [varchar](max) NULL,
[Browser] [varchar](max) NULL
)
WITH
(
DATA_SOURCE = [RemoteReferenceData],
SCHEMA_NAME = 'dbo', -- I missed this part
OBJECT_NAME = 'AuditLog' -- I missed this part
);
So my problem was that I had omitted the SCHEMA_NAME = 'dbo' and OBJECT_NAME = 'AuditLog' which makes a reference to the AuditLog table in DB1. With my OP, Azure was making a reference to AuditLogSource in DB1 which obviously doesn't exist hence I get the error I was getting. BUT, it would help if the query failed in the first place coz that would've highlighted that there was something wrong somewhere. Anyway, I hope this helps someone.
I have created a table which has the columns
Id, name, CountryId,CreatedOn,CreatedBy,updatedOn,UpdatedBy
but when i see the design, there is no CountryId.
When i see script of the created table, it shows CountryId
the script is as follows --
CREATE TABLE [dbo].[State](
[Id] [int] NOT NULL,
[name] [nvarchar](255) NOT NULL,
[CountryId] [int] NOT NULL,
[CreatedOn] [datetime] NULL,
[CreatedBy] [nvarchar](50) NULL,
[UpdatedOn] [datetime] NULL,
[UpdatedBy] [nvarchar](50) NULL,
);
Also, When I right click and select top 100 rows, i find CountryId there. (The following image)
What can be the reason that the design is not showing a column ??
EDIT:
As suggested by shnugo, i was able to solve it after closing and re-opening SSMS 2014
I've excel form which contain macro that can pull data from SQL Server and display info on the excel form. Users can update the form and macro will write changed back to SQL Server.
This is the excel form. Users need to input the values for those highlighted on yellow color. Example John enter user field as 'JOHN' follow by region 'LATAM' , year '2016' and month '3'. Once it done, John would click an 'Retrieve' button to pull all data from SQL Server where Region = LATAM, Year=2016 and Month = 3. All the related info would display on field Area, Region, Mgmt, CompanyCode, AcctUnit, Account and Value (It could have multiple rows of records and users are not allow to edit these records). Now John need to input value for field Comments. Once he completed, John would click 'Save' button and excel macro would write comments value to SQL Server
Here the table structure that excel macro will read and write
CREATE TABLE [dbo].[Sales](
[Region] [varchar](10) NOT NULL,
[Area] [varchar](10) NOT NULL,
[Mgmt] [varchar](10) NOT NULL,
[CompanyCode] [int] NOT NULL,
[AcctUnit] [varchar](7) NOT NULL,
[Account] [varchar](10) NOT NULL,
[Comment] [varchar](100) NULL,
[Year] [int] NULL,
[Jan] [float] NULL,
[Feb] [float] NULL,
[Mar] [float] NULL,
[Apr] [float] NULL,
[May] [float] NULL,
[Jun] [float] NULL,
[Jul] [float] NULL,
[Aug] [float] NULL,
[Sep] [float] NULL,
[Oct] [float] NULL,
[Nov] [float] NULL,
[Dec] [float] NULL,
[SYS_CreatedBy] [varchar](15) DEFAULT SYSTEM_USER,
[SYS_CreatedDate] [datetime] DEFAULT GETDATE(),
[SYS_ModifiedBy] [varchar](15) DEFAULT SYSTEM_USER,
[SYS_ModifiedDate] [datetime] DEFAULT GETDATE(),
CONSTRAINT [PK_Sales] PRIMARY KEY NONCLUSTERED
(
Region ASC,
Area ASC,
Mgmt ASC,
CompanyCode ASC,
AcctUnit ASC,
Account ASC,
)
)
Based on above table structure, how can other users put his/her comments while it doesn't affected those comments that John already updated to SQL Server ? Example, John already input his comments and has been updated to SQL Server, now Alice pull same data from SQL Server where region = LATAM, Year = 2016 and Month = 3. She should get same data as John did except comments field, which in this case should be blank instead of John's comment.
Based on above table design, the comment's value will keep changing by different users. How to redesign table structure so comment can be unique to each users?
I would create a Comments table, and relate it to the Sales table through a foreign key.
To that end, I would add a surrogate key to the Sales table, so that you don't need to add all those PK columns to your Comments table.
When I execute this query, I am getting an error
Cannot find data type dbo.GUID_PK
For this should I create table for CandidateRoleID or what else should I do here?
But, when I googled it I found it saying SQL Server stores GUID. How could I access it or what is the correct way of declaring this table? I searched in google about GUID_PK.
But didn't find any syntax or explanation. Thanks in advance.
CREATE TABLE [dbo].[tbl]
(
[CandidateRoleID] [dbo].[GUID_PK] NOT NULL,
[CandidateID] [uniqueidentifier] NOT NULL,
[RoleID] [int] NOT NULL
);
The SQL server data type for a GUID is UNIQUEIDENTIFIER.
Your script should be:
CREATE TABLE [dbo].[tbl](
[CandidateRoleID] [uniqueidentifier] NOT NULL,
[CandidateID] [uniqueidentifier] NOT NULL,
[RoleID] [int] NOT NULL,
CONSTRAINT PK_Tbl PRIMARY KEY (CandidateRoleID));
If you want it to be 'automatically' created, similar to an integer identity column, give it a default:
CREATE TABLE [dbo].[tbl](
[CandidateRoleID] [uniqueidentifier] NOT NULL DEFAULT NEWID(),
[CandidateID] [uniqueidentifier] NOT NULL,
[RoleID] [int] NOT NULL,
CONSTRAINT PK_Tbl PRIMARY KEY (CandidateRoleID));
CREATE TABLE [dbo].[tbl](
[CandidateRoleID] [uniqueidentifier] primary key NOT NULL,
[CandidateID] [uniqueidentifier] NOT NULL,
[RoleID] [int] NOT NULL,
);
In SQL server GUID is uniqueidentifier data type.
There is no data type 'GUID_PK' in sql server.
GUID is an acronym for Global Unique ID(entifier) and is a unique 16
byte number. The term GUID and UNIQUEIDENTIFIER are often
interchangeable within the SQL Server community.
If you need to auto-generate uniqueidentifier value in your table during data insert, the consider adding default value to the uniqueidentifier data-type.
CREATE TABLE #tbl(
[CandidateRoleID] [uniqueidentifier] NOT NULL DEFAULT NEWID(),
[CandidateID] [uniqueidentifier] NOT NULL DEFAULT NEWID(),
[RoleID] [int] NOT NULL);
GO
INSERT INTO #tbl (ROLEID) SELECT (1)
CandidateRoleID CandidateID RoleID
F20AE15E-8D97-4042-8AA8-DD7BCB0EB6D6 FAE29358-BD34-4BFE-800B-E332375E020E 1
I have the following table
CREATE TABLE [dbo].[LogFiles_Warehouse](
[id] [int] IDENTITY(1,1) NOT NULL,
[timestamp] [datetime] NOT NULL,
[clientNr] [int] NOT NULL,
[server] [nvarchar](150) COLLATE Latin1_General_CI_AS NOT NULL,
[storeNr] [int] NOT NULL,
[account] [nvarchar](50) COLLATE Latin1_General_CI_AS NOT NULL,
[software] [nvarchar](300) COLLATE Latin1_General_CI_AS NOT NULL,
CONSTRAINT [PK_Astoria_LogFiles_Warehouse] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
And want to avoid having duplicate rows in my table. I thought about creating a UNIQUE index on the complete table, but then SQL Manager Studio tells me that this is not possible because the key would be too large.
Is there another way I could enforce unique rows over all columns, apart from indexes?
Create a UNIQUE index on hashed values:
CREATE TABLE [dbo].[LogFiles_Warehouse]
(
[id] [int] IDENTITY(1,1) NOT NULL,
[timestamp] [datetime] NOT NULL,
[clientNr] [int] NOT NULL,
[server] [nvarchar](150) COLLATE Latin1_General_CI_AS NOT NULL,
[storeNr] [int] NOT NULL,
[account] [nvarchar](50) COLLATE Latin1_General_CI_AS NOT NULL,
[software] [nvarchar](300) COLLATE Latin1_General_CI_AS NOT NULL,
serverHash AS CAST(HASHBYTES('MD4', server) AS BINARY(16)),
accountHash AS CAST(HASHBYTES('MD4', account) AS BINARY(16)),
softwareHash AS CAST(HASHBYTES('MD4', software) AS BINARY(16))
)
CREATE UNIQUE INDEX
UX_LogFilesWarehouse_Server_Account_Software
ON LogFiles_Warehouse (serverHash, accountHash, softwareHash)
Use triggers + a smaller non unique index over the most distinguishing ields to helop aleviate the table s can problem.
This goes down a lot into a bad database design to start with. Fields like Software, Account do not belong into that table to start with (or if account, then not client nr). Your table is only so wisde because you arelady violate database design basics to start with.
Also, to abvoid non unique fields, you have NT to have the Id field in the unique testing otherwise you ont ever have doubles to start with.