Insert value with combine the identity column [duplicate] - sql

This question already has answers here:
SQLServer IDENTITY Column with text
(8 answers)
how to create auto increment column with characters and number like alphanumeric in sql server?
(2 answers)
Closed 6 months ago.
Let's say I have this table with the identity column pkid, how can I generate the cust_num as VIP000000 + <pkid> when inserting a record like this?
pkid
cust_name
cust_num
1
Tom
VIP0000001
2
May
VIP0000002
10
John
VIP0000010
CREATE TABLE [dbo].[tbl01]
(
[pkid] [numeric](9, 0) IDENTITY(1,1) NOT NULL,
[cust_name] [varchar](50) NOT NULL,
[cust_num] [varchar](20) NOT NULL
) ON [PRIMARY]

The easiest solution based on an IDENTITY column is to use a computed column - like this:
ALTER TABLE dbo.tbl01
ADD cust_num AS 'VIP' + RIGHT('000000' + CAST(pkid AS VARCHAR(6)), 6) PERSISTED;
Now, every time you insert a row into tbl01 without specifying values for pkid or cust_num:
INSERT INTO dbo.tbl01 (Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically increase your pkid value, and cust_num will contain values like VIP000001, VIP000002,...... and so on - automatically, safely, reliably, no duplicates.
UPDATE
Since you can't change your table definition, you will most likely need to use an AFTER INSERT trigger - something like this:
CREATE TRIGGER trgTbl01AddCustNum
AFTER INSERT
ON dbo.tbl01
AS
BEGIN
UPDATE tbl01
SET cust_num = 'VIP' + RIGHT('000000' + CAST(pkid AS VARCHAR(6)), 6)
FROM tbl01
INNER JOIN Inserted i ON i.pkid = tbl01.pkid;
END;

Related

Generate unique id in SQL Server

How can I create a table with custom ID like 22/00/00001 with a sequence? Sorry I'm a newbie with databases. All help will be appreciated thank you!
I am an intern at a hospital. I have to rewrite a database with SQL Server, I have a problem with specific ID numbers. It must be in year/month/id00001 format, for example 11/22/02586. And each department must have its own patient counter. Any help will be appreciated thanks!.
Example:
CREATE SEQUENCE MySequence
AS INT
START WITH 1
INCREMENT BY 1;
GO
-- Create a new table called 'PATIENT' in schema 'dbo'
-- Drop the table if it already exists
IF OBJECT_ID('dbo.PATIENT', 'U') IS NOT NULL
DROP TABLE dbo.PATIENT
GO
-- Create the table in the specified schema
CREATE TABLE dbo.PATIENT
(
NUM_PAT [VARCHAR] (20) NOT NULL
PRIMARY KEY
CONSTRAINT [DF_PATIENT_ID_PATIENT]
DEFAULT FORMAT ((NEXT VALUE FOR MySequence), '22/00/00000#'), -- primary key column
NOM_PAT [VARCHAR](50) NOT NULL,
PREN_PAT [VARCHAR](50) NOT NULL,
DN_PAT [DATE] NOT NULL,
-- specify more columns here
);
GO
-- Insert rows into table 'PATIENT'
INSERT INTO PATIENT ([NOM_PAT], [PREN_PAT], [DN_PAT])
VALUES ('fred', 'alves', '25/11/1990'),
('alvaldo', 'merlin', '11/09/1985');
-- add more rows here
GO
I'm checking your request, I think you can aproach in two way, a way is define a table where you will save the patient id and a column with counter to generate your custom id
Example
Table name like PatientCounter
PatientID, PatientCounter
1 1
2 125
Or in table patient add a column Counter, I prefer the thing separeted, but this also is a option, then in the query you could do something like that.
DECLARE #PatientId as int
DECLARE #PatientCount as int
SET #PatientId = 21
SET #PatientCount = 1
SELECT
CAST(FORMAT(GETDATE(),'yy') as nvarchar(4)) + '/' +
CAST(MONTH(getDATE()) as nvarchar(4)) + '/' +
CAST(#PatientId as nvarchar(10)) +
CAST(REPLICATE('0', 5 - LEN(#PatientCount + 1)) + RTrim(#PatientCount + 1) as nvarchar(50)) as MyCustomId
The result
MyCustomId
22/11/2100002
And after confirming that your application has consumed this custom id, update the counter in the table.
UPDATE PatientTable SET PatientCount = PatientCount + 1 WHERE PatientID = #PatientId
Best Regards

How to create a query to join multiple rows from a different table into single comma delimated column in SQL Server [duplicate]

This question already has answers here:
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
Closed 4 years ago.
I am using SQL Server 2014, and I have two tables:
number id
------------------
36-23 1
36-23 2
id value
------------------
1 asia
2 europe
The number column is of type varchar. I want to write a query to return the following results:
number Name
---------------------------
36-23 asia,europe
I am wondering how can I do this with the help of query or functions in SQL Server.
I think using STUFF is the easiest way to go forward here.
CREATE TABLE tableID
([number] varchar(50), [id] int)
;
INSERT INTO tableID
([number], [id])
VALUES
('36-23', 1),
('36-23', 2)
;
CREATE TABLE tableLoc
([id] int, [value] varchar(50))
;
INSERT INTO tableLoc
([id], [value])
VALUES
(1, 'asia'),
(2, 'europe')
;
SELECT tableID.number, tableLoc.value INTO temp1
FROM tableID INNER JOIN tableLoc ON tableID.id = tableLoc.id;
SELECT *, STUFF((
SELECT DISTINCT ', ' + value
FROM temp1
WHERE number = t.number
FOR XML PATH('')), 1, 2, '')
FROM (
SELECT DISTINCT number
FROM temp1
) t

How To Insert 2 Values in 2 columns and rest null values in rest columns without using Create Table Statement

Please Check this Sample Sql fiddle:http://www.sqlfiddle.com/#!3/f59ae.
In this way only i want output.first 2 columns Should contain values that can be anything
and rest columns should contain Hello values without considering Create Table statement.
I want to write a query that will insert 2 values into 2 columns and Hello into all other columns.
Suppose I have 100 columns then I want 10 and 20 values to be inserted into col1 and col2 and Hello into all other 98 columns.
Likewise if I have 200 columns then I want 10 and 20 values to be inserted into col1 and col2 and Hello into the other 198 columns.
I have written a query which but I thought it's a basic query so I am not writing here. So downvoters please consider that.
How to write this query???
You can do this by just adding the Default constraint to column's which you don't want to insert values explicitly. I hope #Manish Pant's answer should help you to do that.
Based on your comments you want do this only by using query. So you need to use Dynamic sql to do this.
Simple Demo
Schema
CREATE TABLE [dbo].[Test](
[id] [int] IDENTITY(1,1) NOT NULL,
[Country] [varchar](100) NULL,
[State] [varchar](100) NULL,
[City] [varchar](100) NULL,
[Population (in Millions)] [varchar](100) NULL
)
Declare a variable to hold the Dynamic sql
DECLARE #cl_val NVARCHAR(max)='Insert into Test('
Pull all the columns from sys.columns view and filter the identity column
SELECT #cl_val += Quotename(NAME) + ','
FROM sys.columns
WHERE Object_name(object_id) = 'Test'
AND is_identity <> 1
ORDER BY NAME
SELECT #cl_val = LEFT(#cl_val, Len(#cl_val)-1) + ') values (' -- Remove the trailing comma
Here add the values only to the column in case statement which you are explicitly passing value in else part add the default value
SELECT #cl_val += CASE
WHEN NAME ='City' THEN '''A'''
WHEN NAME='country' THEN '''c'''
ELSE '''Hello'''
END + ','
FROM sys.columns
WHERE Object_name(object_id) = 'Test'
AND is_identity <> 1
ORDER BY NAME
SELECT #cl_val = LEFT(#cl_val, Len(#cl_val)-1) + ')' -- Remove the trailing comma
--PRINT #cl_val
EXEC Sp_executesql #cl_val
select * from test
Result
id Country State City Population (in Millions)
-- ------- ----- ---- ------------------------
1 c Hello A Hello
If All other columns are set as Nullable then into your Insert statement you can write statement By without considering your Nullable fields.
Suppose for example your Table named Student with properties is:
Student ::
Name,
RollNo,
OptionalField_1,
OptionalField_2,
OptionalField_3
where columns with OptionalField are Nullble fields.
In this case you can write your Query simply as ::
INSERT INTO Student (Name,RollNo) VALUES ('MyName',12);
So this will make an ENtry with two column values & all remaining as Nullable.
For your better understandings you can refer :: http://www.w3schools.com/sql/sql_insert.asp
You can use this for your query:
create table mytable(
col1 varchar not null,
col2 varchar not null,
col3 varchar not null default 'Hello',
col4 varchar not null default 'Hello',
col5 varchar not null default 'Hello',
so on...... );
insert into mytable(col1,col2) values('10','20');

Retrieve a column from a table then insert it to a new table

I just created a table in SQL 2008. This table has two columns.
CREATE TABLE [dbo].[MyTable]
(
[pkey] [bigint] not null,
[Number] [int] not null
)
Now I want to insert values into it. The first column can be obtained from another table dbo.OldTable. It has many records and I don't want to manually insert the data. The second column Number can be a 0 in each row. What is the best way to do this?
you can do a bulk processing of your table data.
INSERT INTO MyTable
(pkey, Number)
SELECT pkey, 0
FROM OtherTable
INSERT INTO [dbo].[MyTable](pkey, Number)
SELECT Column, 0
FROM dbo.OldTable

INSERT INTO With a SubQuery and some operations

I'm trying to insert some data to a table contains two things : "a string" and "maximum number in Order column + 1".
This is my query:
INSERT INTO MyTable ([Text],[Order])
SELECT 'MyText' , (Max([Order]) + 1)
FROM MyTable
What is going wrong with my query?
I'm using Microsoft SQL Server 2005 SP3.
You can test this query like this:
I don't receive error:
create table #MyTable
(
[Text] varchar(40),
[Order] int NOT NULL
)
INSERT INTO #MyTable([Text],[Order])
SELECT 'MyText' [Text], isnull(max([order]) + 1, 0) [Order]
FROM #MyTable
drop table #MyTable
Original:
INSERT INTO MyTable ([Text],[Order])
SELECT 'MyText' [Text], max([Order]) + 1 [Order]
FROM MyTable
or
INSERT INTO MyTable ([Text],[Order])
SELECT top 1 'MyText' [Text], max([Order]) + 1 [Order]
FROM MyTable
limit is not valid in SQL Server as far as I know.
Cannot insert the value NULL into column 'Order', table 'master.dbo.MyTable'; column does not allow nulls. INSERT fails. The statement has been terminated.
This means that the Order column isn't allowed to be null, and that the Max([Order]) + 1 part of your column returns NULL.
This is because your table is empty, as you already noticed by yourself.
You can work around this by replacing NULL by a real number in the query, using ISNULL():
INSERT INTO MyTable ([Text],[Order])
SELECT 'MyText' , (isnull(Max([Order]),0) + 1)
FROM MyTable
Unless he has a column named OrderBy
then he would have to add / assign all values within that Insert especially if the column does not allow for nulls
sounds like fully qualifying the Insert with the dbo.MyTable.Field may make more sense.
also why are you naming fields with SQL Key words...???
INSERT INTO MyTable ([Text],[Order] Values('MyTextTest',1)
try a test insert first..