Define column name which only takes 10 digit number in SQL - sql

I have the following code in for a SQL TABLE
CREATE TABLE [dbo].[Table_1](
[ID] [int] NULL,
[StudentID] [nvarchar](10) NULL,
[Name] [nvarchar](50) NULL,
[Address] [nvarchar](500) NULL,
[Phone] [nvarchar](10) NULL
) ON [PRIMARY]
GO
But I can insert any value for StudentID. I want to insert 10 digit number, if it is less/greater then 10 digit it shouldn't take the value. Can anyone help me with this since I am new to SQL. Thank you

If you want StudentId to be ten digits, you can define a check constraint. In SQL Server, this would look like:
alter table table_1 add constraint chk_table_1_student_id
check (student_id like '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]');
If you don't like counting expressions in strings, you can also specify:
alter table table_1 add constraint chk_table_1_student_id
check (len(student_id) = 10 and student_id not like '%[^0-9]%');
That is, it has a length of 10 and no non-digit characters.

Related

Replacing a trigger with a stored procedure

I'm trying to replace a trigger statement with a stored procedure since enabled triggers are not allowed when using the tables in microsoft powerapps.
Simplified, I have to tables:
KPI_Dim (KPI_ID [PK] , KPIName, KPIGroup...)
KPICurrent_Fact (KPI_key [FK i.e KPI_Dim[KPI_ID], KPICurrent_ID, KPI_Value...)
Currently, for every new record in KPI_Dim my trigger adds a new row in KPICurrent_Fact with the FK and an autoincremented PK. The rest of the columns e.g. KPI_Value are supposed to be empty.
My simple trigger looks like this:
CREATE TRIGGER [dbo].[trg_insert_newKPI]
ON [dbo].[KPI_Dim]
FOR INSERT AS
INSERT INTO KPICurrent_Fact (KPI_key)
SELECT KPI_ID
FROM INSERTED
Now, I want to create a stored procedure that can achieve exactly the same. I have tried to find a solution myself but I'm new to stored procedures and could not find anything that would replicate a trigger.
I'm using SSMS v.18.4.
Thank you for any suggestions.
EDIT
Added Table creation and insert into statement code.
/* Create KPI_Dim table*/
CREATE TABLE [dbo].[KPI_Dim](
[KPI_ID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[KPIName] [varchar](200) NOT NULL,
[KPIDescription] [varchar](500) NULL,
[KPIGroup] [varchar](100) NOT NULL,
[KPISubGroup] [varchar](100) NULL,
[KPIOwner] [varchar] (50) NOT NULL,
[DateCreated] DATETIME NULL DEFAULT(GETDATE())
)
/* Example data */
INSERT INTO [dbo].[KPI_Dim]
(
KPIName,
KPIDescription,
KPIGroup,
KPISubGroup,
KPIOwner
)
VALUES
('TestKPIName','testtest','TestGroup', 'TestSubGroup', 'TestOwner');
You can go for OUTPUT Clause and insert into table variable. From the table variable, you can insert into fact table.
CREATE TABLE [dbo].[KPI_Dim](
[KPI_ID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[KPIName] [varchar](200) NOT NULL,
[KPIDescription] [varchar](500) NULL,
[KPIGroup] [varchar](100) NOT NULL,
[KPISubGroup] [varchar](100) NULL,
[KPIOwner] [varchar] (50) NOT NULL,
[DateCreated] DATETIME NULL DEFAULT(GETDATE())
)
CREATE TABLE dbo.KPI_Fact
(
[KPI_ID] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[KPIDIMID] INT NULL FOREIGN KEY references [dbo].[KPI_Dim]([KPI_ID])
)
DECLARE #inserted table(KPI_DIMID INT)
INSERT INTO [dbo].[KPI_Dim]
(
KPIName,
KPIDescription,
KPIGroup,
KPISubGroup,
KPIOwner
)
OUTPUT inserted.KPI_ID INTO #inserted
VALUES
('TestKPIName','testtest','TestGroup', 'TestSubGroup', 'TestOwner');
INSERT INTO dbo.KPI_Fact([KPIDIMID])
SELECT * FROM #inserted
KPI_ID
KPIDIMID
1
1

Timestamp column not saving data in sql table

Hi I am designing table called user-registration with few fields. I have created date and updated date and requirement is to put time stamp for created and updated fields. I googled and found only one time stamp we can have per table and value will be inserted automatically and no need to supply value to it. Please correct me if i am wrong. Currently when i insert row of data to table i am getting in time stamp field. Below is my table structure.
CREATE TABLE [dbo].[NCT_UserRegistration](
[User_Id] [int] IDENTITY(1,1) NOT NULL,
[User_EmailId] [varchar](255) NULL,
[User_Password] [varchar](512) NULL,
[User_Name] [varchar](255) NULL,
[User_MobileNum] [varchar](20) NULL,
[User_Status] [varchar](15) NULL CONSTRAINT chk_Status CHECK ([User_Status] IN ('ENABLED', 'DISABLED')),
[User_Role] [varchar](20) NULL CONSTRAINT chk_Role CHECK ([User_Role] IN ('SUPER_ADMIN','PROJECT_ADMIN')),
[User_CreatedDate] [timestamp] NULL,
[User_UpdatedDate] [datetime] NULL,
[Name] [varchar](30) NULL
)
I tried as below.
ALTER TABLE [NCT_UserRegistration]
ALTER COLUMN [User_CreatedDate] TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
and ended up with Incorrect syntax near the keyword 'DEFAULT'.
Any help would be appreciated. Thank you.
Try this in Table structure :-
User_CreatedDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

SQL query not returning record

I am trying to retrieve a record from a table with a given field value. The query is:
declare #imei varchar(50)
set #imei = 'ee262b57-ccb4-4a2b-8410-6d8621fd9328'
select *
from tblDevices
where imei = #imei
which returns nothing.
If I comment out the where clause all records are returned, including the one I am looking for. The value is clearly in the table field and matches exactly, but I cannot get the where clause to work.
I literally copied the value out of the table to ensure it was correct.
I would appreciate any guidance on my mistake.
Table def:
CREATE TABLE [dbo].[tblDevices](
[id] [int] IDENTITY(1,1) NOT NULL,
[create_date] [datetime] NOT NULL,
[update_date] [datetime] NOT NULL,
[other_id] [int] NULL,
[description] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[authorized] [int] NOT NULL,
[imei] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
CONSTRAINT [PK_tblDevices] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
Edit
Using user2864740 suggestion, I queried the following:
select hashbytes('SHA1', imei) as h1 from tblDevices where id =8
returns:
0x43F9067C174B2F2F2C0FFD17B9AC7F54B3C630A2
select hashbytes('SHA1', #imei) as h2
returns:
0xB9B82BB440B04729B2829B335E6D6B450572D2AB
So, I am not sure what this means. My poor little brain is having a hard time understanding that A <> A?! What is going on here if it's not a collation issue? How can two identical values not be considered equal?
Edit 2
this is the table record I want:
8 2013-10-22 12:43:10.223 2013-10-22 12:43:10.223 -1 1 ee262b57-ccb4-4a2b-8410-6d8621fd9328
Kinda of taking a wild stab but with the two hashes showing they are in fact different, wondering if you just have an extra space somewhere Maybe try:
select *
from tblDevices
where Trim(imei) = (#imei)

How do I insert into two tables all at once in a stored procedure? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How can I INSERT data into two tables simultaneously in SQL Server?
Doing a project for school so any help would be great thank you!
I have two tables - how do I insert into two tables? So both tables are linked.
First table is called Customer with primary key called CID that auto increments
CREATE TABLE [dbo].[Customer](
[CID] [int] IDENTITY(1,1) NOT NULL,
[LastName] [varchar](255) NOT NULL,
[FirstName] [varchar](255) NOT NULL,
[MiddleName] [varchar](255) NULL,
[EmailAddress] [varchar](255) NOT NULL,
[PhoneNumber] [varchar](12) NOT NULL
CONSTRAINT [PK__CInforma__C1F8DC5968DD69DC] PRIMARY KEY CLUSTERED
(
And a second table called Employment that has a foreign key linked to the parent table
CREATE TABLE [dbo].[Employment](
[EID] [int] IDENTITY(1,1) NOT NULL,
[CID] [int] NOT NULL,
[Employer] [varchar](255) NOT NULL,
[Occupation] [varchar](255) NOT NULL,
[Income] [varchar](25) NOT NULL,
[WPhone] [varchar](12) NOT NULL,
CONSTRAINT [PK__Employme__C190170BC7827524] PRIMARY KEY CLUSTERED
(
You need to do something like this:
DECLARE #NewID INT
INSERT INTO Customer(LastName,FirstName,......) VALUES(Value1, Value2, .....)
SELECT #NewID = SCOPE_IDENTITY()
INSERT INTO Employment(CID,Employer,.....) VALUES(#NewID, ValueA,..........)
SCOPE_IDENTITY: Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.

SQL Server IDENTITY column

How can I modify this command in order to have an identity column which has five digits integer like 00000 and start from 00001 ?
CREATE TABLE [dbo].[Company]
(
[CompanyId] [bigint] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](200) NOT NULL
)
An integer does not have any leading 0 by itself. It is a formatting issue to deal with when converting the integer to a string for displaying.
If you really, really need to be able to present such a string right out of SQL, you can do it with a computed column:
CREATE TABLE [dbo].[Company](
[CompanyId] [bigint] IDENTITY(1,1) NOT NULL,
[FormattedCompanyId] AS RIGHT('0000'+ CONVERT(VARCHAR,Num),5),
[Name] nvarchar NOT NULL,
I would never use that solution myself though, formatting doesn't belong in the data store.
You need to add the leading zeros yourself. As a solution you can add an other colomn named say "formatedID" and update it with an "after insert trigger" with the value from the identity column and formatted with the leading zeros you want to.
Example :
CREATE TABLE [dbo].[Company]
(
[CompanyId] [bigint] IDENTITY(1,1) NOT NULL,
[FormattedID] [VARCHAR(20)],
[Name] [nvarchar](200) NOT NULL
)
CREATE TRIGGER ON [dbo].[Company]
FOR INSERT
AS
BEGIN
UPDATE [dbo].[Company]
FROM inserted
SET FormattedID = RIGHT('0000'+ CONVERT(VARCHAR, [dbo].[Company].CompanyId),5)
WHERE dbo.Company.CompanyId = inserted.CompanyId
END