I have this table called businessname (id, name) and I need to insert data into this table but before that I need to check for similar name is existing in the table. this table called similarwords display below.
id | words
===============================
1 | transport, travel
-------------------------------
2 | IT, information technology
-------------------------------
3 | builders, contractors
-------------------------------
As example-> If there is business name called "ABCD transport" when user try to insert "ABCD travel" it should validate & give error message "Similar name already exists." is there way to do this in SQL ?
You can try a procedure like this to insert data -
CREATE PROCEDURE DATA_INSERT (#ID INT, #NAME VARCHAR(100))
AS BEGIN
IF EXISTS (SELECT * FROM BUSINESSMAN WHERE NAME = #NAME)
BEGIN
PRINT ('Similar name already exists')
END
ELSE
BEGIN
INSERT INTO BUSINESSMAN VALUES (#ID, #NAME)
END
END
EXEC DATA_INSERT 4,'ABCD TRANSPORT'
Although I will suggest you to create an primary key on that column if you doesn't want duplicates to be inserted.
Related
create table using select statement in place of table_name.
I want to create a table with the name B100 where '100' is the maximum value of id in table 'A'
example:
table A:
id name
100 harsh
78 Vishal
23 Ivan
34 Hardik
need to create table with name 'B{max_value_of_id_in_A}'.
the fields in table B is the same (id, name);
what I try:
create table CONCAT('B', (Select max(id) from A))
(
id int,
name varchar(50)
)
To do this, you need to use dynamic sql. A quick and dirty example is:
create table test(id smallint, name varchar(15));
insert test (id, name) values
(98, 'harsh'), (78, 'Vishal'), (23, 'Ivan'), (34, 'Hardik');
declare #sql nvarchar(200);
set #sql = N'create table B' + format((select max(id) from test), 'D3')
+ N'(
id int,
name varchar(50)
);'
select #sql;
exec(#sql);
exec('select * from B098');
Notice that I had to resort to dynamic sql to actually use that table within the same batch. As the others have suggested, you should reconsider the path you have chosen for many reasons. Perhaps foremost is that this requires a rather advanced level of skill - you will likely need much help to make use of your table. You should consult with your DBA to get their opinion (and permission).
I am trying to create a trigger with a higher difficulty that would let me create a log after updating rows in alumns table
| Alumn_ID | Name | Courses | Favourite_Course
1 Peter 5 Math
And this would be the result if for example someone updated the number of courses from 5 to 6.
| Log_ID | Alumn_ID | Note | NoteID | Change_Date | Last_Change_Date
1 1 Fields were Updated Note 1 2018-04-23 00:00:00.000 2018-03-23 00:00:00.000
Here is my current trigger
ALTER TRIGGER [LOG]
ON ALUMNS
AFTER UPDATE
AS
BEGIN
DECLARE #Note VARCHAR(50)
DECLARE #Alumn_ID varchar;
SELECT #Alumn_ID= INSERTED.Alumn_ID FROM INSERTED
SET #Note = 'Fields were updated'
INSERT INTO Alumn_Log (Log_ID, Alumn_ID, Note, NoteID, Change_Date)
SELECT Log_ID, i.Alumn_ID, #Note, NoteID, GETDATE(); FROM INSERTED i
END
My problem is:
How do i create the Log ID and the Note ID that i can't take from INSERTED i?
My second problem is, how do i insert the current date? when i try to execute the query it tells me that i can't use that variable in INSERTS.
My third problem, is how can i put the "Last change date"?
Fourth, is there a way to type an specific Note for example if only the name was changed it should say "Name was changed"?
Finally, The Note ID would be Varchar not identity and every note ID needs to be different
This is the current and only error that's preventing me from running the Query:
This is what i get Msg 273, level 16, state 1, procedure Log_Trigger, line 19 [Batch Start Line 0] me time stamp Use INSERT with a list of columns to exclude the timestamp column or insert DEFAULT in the timestamp column.
Here is how I would approach it.
How do i create the Log ID and the Note ID that i can't take from
INSERTED i?
The Log Id can be an AutoIdentity column. An INT column with IDENTITY INSERT.
The Note ID can be an Auto Incremented Computed column (shown in the code below). You would probably need to introduce a new column that serves as a prefix.
My second problem is, how do i insert the current date? when i try to
execute the query it tells me that i can't use that variable in
INSERTS.
GETDATE()?
My third problem, is how can i put the "Last change date"?
You can have a join with INSERTED and get the value from the log from a previous row. Shown in the code.
Fourth, is there a way to type an specific Note for example if only
the name was changed it should say "Name was changed"?
That would depend on finding the nature of the update on which column. This is more of a business question than a technical question.
Finally, The Note ID would be Varchar not identity and every note ID needs to be different
Now, the code (the entire schema)
CREATE TABLE LOG(
Log_ID INT IDENTITY(1, 1) NOT NULL,
Alumn_ID INT,
NOTE VARCHAR(200),
PREFIX VARCHAR(30),
NOTEID AS([PREFIX] + RIGHT('0000000' + CAST(Log_ID AS VARCHAR(7)), 7)) PERSISTED,
CHANGEDATE DATETIME,
LASTCHANGEDATE DATETIME
);
CREATE TABLE ALUMN(
Alumn_ID INT,
NAME VARCHAR(50),
COURSES INT,
FAVORITE_COURSE VARCHAR(50)
);
CREATE TRIGGER[trg_LOG]
ON ALUMN
AFTER UPDATE
AS
BEGIN
DECLARE #Note VARCHAR(50)
--DECLARE #Alumn_ID VARCHAR(50)
DECLARE #Lastchange DATETIME
--SELECT #Alumn_ID = INSERTED.Alumn_ID FROM INSERTED
SET #Note = 'Fields were updated'
SELECT #Lastchange = CHANGEDATE FROM LOG l
INNER JOIN INSERTED i ON l.Alumn_ID = i.Alumn_ID
--INNER JOIN ALUMN
INSERT INTO LOG(Alumn_ID, Note, Prefix, CHANGEDATE, LASTCHANGEDATE)
SELECT i.Alumn_ID, #Note, 'AUP', GETDATE(), #Lastchange FROM INSERTED i
END
how do i insert the current date? when i try to execute the query it
tells me that i can't use that variable in INSERTS.
SELECT Log_ID, i.Alumn_ID, #Note, NoteID, GETDATE(); FROM INSERTED i
Take the semi-colon out of the line above.
SELECT Log_ID, i.Alumn_ID, #Note, NoteID, GETDATE() FROM INSERTED i
I'm getting it within the body my AddPartner stored procedure:
-- Create stored procedure for inserting a partner and returning the id of that inserted partner
CREATE PROCEDURE AddPartner (#name NVARCHAR(50),
#email NVARCHAR(254),
#new_guid UNIQUEIDENTIFIER OUTPUT)
AS
BEGIN
SET NOCOUNT ON
INSERT INTO Partners (name, email)
OUTPUT INSERTED.id INTO #new_guid
VALUES (#name, #email)
END
Then later I'm getting
Could not find stored procedure 'AddPartner'.
but I'm supposing this is related the aforementioned error? I'm trying to use it so that I can get the id of the newly inserted item and use that to insert in a related table:
DECLARE #first_partner_id AS UNIQUEIDENTIFIER
EXEC AddPartner 'Haliburton', 'DCheney#Haliburton.org', #first_partner_id OUTPUT;
INSERT INTO Partners (name, email)
VALUES ('Berkshire Hathaway', 'WarrenBridgemaster#bershire.org');
INSERT INTO Partners (name, email)
VALUES ('Jason', 'jason89#gmail.com');
-- Partners
-- ============================================================
-- id | name | email
-- ============================================================
-- 1 | 'Haliburton' | 'DCheney#Haliburton.org'
-- 2 | 'Berkshire Hathaway' | 'WarrenBridgemaster#bershire.org'
-- 3 | 'Jason' | 'jason89#gmail.com'
INSERT INTO Answers (question_id, partner_id, val)
VALUES (1, #first_partner_id, 24);
INSERT INTO Answers (question_id, partner_id, val)
VALUES (1, #first_partner_id, 50);
INSERT INTO Answers (question_id, partner_id, val)
VALUES (3, #first_partner_id, 90);
Where am I going wrong here?
As stated in #MohammadSanati answer, OUTPUT can only insert into a table or table variable.
So it assumes #new_guid is a table variable but can't find it declared. (its declared as a UNIQUEIDENTIFIER not a table). Because of this your CREATE PROC fails.. subsequently when you try and call it it can't find it and you get 'Could not find stored procedure....
So you need to declare a table variable after your BEGIN, something like this:
DECLARE #OutputTable TABLE (AColumn UNIQUEIDENTIFIER)
Then use it like this:
OUTPUT INSERTED.id INTO #OutputTable (AColumn)
Then load it into your output variable like this:
SELECT TOP 1 #new_guid = AColumn FROM #OutputTable
Note: if more than one record is generated this just picks an arbitrary one.
based on following document, the output variable must be a table variable
<OUTPUT_CLAUSE> ::=
{
[ OUTPUT <dml_select_list> INTO { #table_variable | output_table } [ ( column_list ) ] ]
[ OUTPUT <dml_select_list> ]
}
Output INSER
I have a table called CompanyMaster_tbl with a table structure as follows.
Cid CompanyName Deleted
and another table named DepartmentMaster_tbl,with a table structure as follows.
dtld dtname dtphone dtemail cid deleted
I've written a stored procedure for inserting data into these tables as follows.
CREATE PROCEDURE [dbo].[InsertDetails](
#companyName varchar(150),
#dname varchar(150),
#dphon varchar(150),
#deleted int,
#cid int OUTPUT
) AS
BEGIN
INSERT INTO [dbo].CompanyMaster_tbl
VALUES (#companyName)
select #cid=cid
from [dbo].CompanyMaster_tbl
WHERE ##ROWCOUNT > 0 AND cid = scope_identity()
insert into DepartmentMaster_tbl
values(#dname,
#dphon)
end
When I execute this SP, i am getting error like this:
Column name or number of supplied values does not match table definition.
try this , mention coloumn name
INSERT INTO [dbo].CompanyMaster_tbl (CompanyName )
VALUES (#companyName)
INSERT into DepartmentMaster_tbl (dname,dphon)
values(#dname, #dphon)
You are giving wrong number of values to the table i.e. you have two columns in table CompanyMaster_tbl(i think your cid is identity(auto generated) there fore i did not mention it) but you can give only one value to the table, and same thing applies for DepartmentMaster_tbl. if you can't give the values to the table then mention column names in the insert statement otherwise give all column value
e.g.
Insert into CompanyMaster_tbl(CompanyName) values(#companyName)
or
Insert into CompanyMaster_tbl values(#companyName, #deleted)
We have .mdb file with hundreds of tables: Lesson1, Lesson2, Lesson3, Lesson4, etc. All tables have the same structure:
Lesson<n>
----------------
slide_id
name
description
status
created_date
created_by
updated_date
updated_by
What SQL statement would generate a result like this:
| table_name | slide_id | name |
|-----------------------|-------------------------------|
| Lesson1 | 1 | name for slide 1 of lesson 1 |
| Lesson1 | 2 | name for slide 2 of lesson 1 |
| Lesson2 | 1 | name for slide 1 of lesson 2 |
| Lesson2 | 2 | whatever |
| Lesson2 | 3 | again whatever |
etc.
So there are a few points here:
table names must be included
there are hundreds of tables
If the table names are known, you can create a query like:
SELECT 'Lesson1' AS table_name, slide_id, name, ... FROM Lesson1
UNION ALL SELECT 'Lesson2', slide_id, name, ... FROM Lesson2
UNION ALL SELECT 'Lesson3', slide_id, name, ... FROM Lesson3
UNION ALL SELECT 'Lesson4', slide_id, name, ... FROM Lesson4
UNION ALL SELECT 'Lesson5', slide_id, name, ... FROM Lesson5
Cursors are only needed if the number of tables is in constant flux. If not, this should do the trick.
Hint: to generate the initial query, paste the names of the table in Excel, and use a formula in the next cell over to create that table's "UNION ALL" statement. Then copy and paste straight back into Access. (Or create it dynamically using a cursor, but copy/paste and a quick formula is easy, and you can save the excel file just in case you need to add tables in bulk, change the columns selected, etc.)
And, obviously, the end solution should be to consolidate the tables, if possible, and add a discriminator field when querying. Heck, if you have to, it's easier to maintain hundreds of queries that each pull one lesson's rows (again, Excel can be a handy batch-update tool), than hundreds of lessons tables that must have identical structures.
Using sql server, I can unfortunately see this only done with a CURSOR X-(.
This should help
DECLARE #Name VARCHAR(50)
DECLARE Cur CURSOR FOR
SELECT name
FROM sysobjects
WHERE xtype = 'U'
and name like 'Lesson%'
OPEN Cur
FETCH NEXT FROM Cur INTO #Name
DECLARE #RetTable TABLE(
TableName VARCHAR(50),
slide_id INT,
name VARCHAR(100)
)
WHILE ##FETCH_STATUS = 0
BEGIN
INSERT INTO #RetTable EXEC ('SELECT ''' + #Name + ''',slide_id , Name FROM ' + #Name)
FETCH NEXT FROM Cur INTO #Name
END
CLOSE Cur
DEALLOCATE Cur
SELECT *
FROm #RetTable
OK, then if you can use a macro/vba code you can create a temp table called AllLessons and run the following code. I tested this from a form with a button.
Private Sub Command0_Click()
Dim iTable As Integer
For iTable = 0 To CurrentDb.TableDefs.Count - 1
Dim tableName As String
tableName = CurrentDb.TableDefs(iTable).Name
If (Left(tableName, Len("Lesson")) = "Lesson") Then
CurrentDb.Execute "INSERT INTO AllLessons ([table_name],[slide_id],[name]) SELECT """ & tableName & """, [slide_id],[name] FROM " & tableName
End If
Next iTable
End Sub