Can I create a table with check constrain whose values are dependent on sql query - sql

Is it possible to create a table which has a check constraint on one of the column whose value lies within the result set given by another sql query
eg.
create table tablename
(
name varchar(10),
rollno int
)check rollno in (select rollno from anotherDatabase.TableName,candidateRoll)
or any thing like that.
I dont have to use it anywhere but still want to know.

If you can't achieve what you want with a foreign key reference, so you can if you wrap the SELECT statement in a function call.
Your check constraint expression may look something like:
(dbo.SomeFunction([col1]) != 0)
The function might look like this (assuming the column is a varchar):
create function dbo.SomeFunction(#arg varchar(max))
returns bit
as
begin
return
(
select count(*) from SomeOthertable where col2 = #arg
)
end
EDIT (2010/06/9): Regarding Anthony's comment, my testing has shown that a count(*) value of greater than 1 is still returned as 1. So it would seem that the function is okay, even though it should probably explicitly return 1 or 0. Or, if you are interested in the actual rowcount, change the return type from BIT to INT.

Yes: foreign key for same database links
create table tablename
(
name varchar(10),
rollno int FOREIGN KEY (candidateRoll) REFERENCES OtherTableName (candidateRoll)
)
If it's a different database then use code e.g. insert via stored proc or enforce via a trigger

Related

SQL Server - how to update the ID column after inserting new records

I need to update a SQL Server table periodically by inserting new records into it.
The table has an ID column in the form of Company0001 through Company0020 right now.
Let's say I added one record of a new company into the table. I want to fill the ID column with Company0021 for this new record. Can anyone suggest a way to do this?
Thank you so much!
I would strongly suggest to use an identity column. Identity is a mechanism designed and used for this actual purpose and therefore it would be much better in terms of performance.
Nevertheless, if you insist on IDs on the format 'CompanyXXX' I would suggest to use a varchar column. Then you would add a trigger on the insert and update operations. When the trigger runs, it would find out the last 'CompanyXXX' and form the new one. If you need help regarding triggers, you could check this tutorial.
Hope I helped!
My suggestion would be to have an autoincrement field, and then concatenate the company name with the ID.
If you don't want to do it with an ID field, do you want it to happen automatically, or are you going to manage it manually? If automatically, you'll need to write a trigger to intercept the INSERT and change the value there. Shouldn't be too hard to do.
I'd seriously recommend NOT doing this and going down the autoincrement field path. It's better.
Add another column to the table to hold an integer value (in this example SNo) and then write query as
declare #SNo int
select #SNo=max(SNo)+1 from Table_Name
insert into Table_Namevalues (#SNo,'company'+right('0000'+cast(#SNo as varchar(10)),4))
And then see the result
Hope this helps
In case a solution is required as, having only one column with values in desired format you can create a function as:
create table table1(id varchar(100));
Go
create function dbo.fn_GetCompanyIdentity ()
returns varchar(100)
as
begin
declare #CompanyIdentify varchar(100);
select #CompanyIdentify =
(select 'Company' +
right ('00000' + cast (
(
(
case when Not exists (select ROW_NUMBER() over( order by (select 1)) from Table1 ) then 1
else (select top 1 ROW_NUMBER() over( order by (select 1)) as currentRownumber from Table1 order by currentRownumber desc) + 1
end
)
)
as varchar(4))
,4));
return #CompanyIdentify;
end;
go
and then use the function in insert statement as :
insert into Table1 (id)
select dbo.fn_GetCompanyIdentity();
Go
Hope this helps!!
Why dont you just create an auto-increment column and then concatenate "Company" to this column in another column. And for presentation just select "Company+autoincrement" column.

Having data from another table put in into check constraint

I have table say table1 with a colum say checkColumn,
now I want to put a check constraint to the field checkColumn which would allow only data which is there in another table say table 2 for some conditions,
I tried this like this,
ALTER TABLE table1
ADD CHECK (checkColumn=(select field1 from table2 where field2='ABC') ) //the select is not scalar
but as I realized it doesn't allow sub-query string in the check condition,I searched a little and read I should use a foreign key,or trigger, or something else,but didn't really understand how to implement those examples here,so posting this as a separate question.
Unfortunately you can not insert Sub Query into context of Check constraint. But here I would like give suggestion, You can use any trigger or function , You can use
foreign key constraint to check data dependency
I would like to share one example with function.
e.g.
CREATE FUNCTION fn_Check_Rollnumber (
#Rollnumber INT
)
RETURNS VARCHAR(10)
AS
BEGIN
IF EXISTS (SELECT Rollnumber FROM Table_Student WHERE Rollnumber = #Rollnumber)
return 'True'
return 'False'
END
Now you can use this function in you Check context like,
ALTER TABLE Table_Fees
WITH CHECK ADD CONSTRAINT CK_RollCheck
CHECK (fn_Check_Rollnumber(Rollnumber) = 'True')

Can I use a type of an existing table's column when creating a table?

I am curious if I could use the type of an existing table's column when I create another column. Just as using a data type like varchar, I would like to have my column the same type as a column in another table.
I am imagining something like
CREATE TABLE FIRST (id NUMBER(5), name VARCHAR(25))
and then
CREATE TABLE SECOND (id NUMBER(6), value FIRST.NAME%TYPE)
and the type of the VALUE column would be VARCHAR(25)
I see this as a generic SQL question, though I am using Oracle.
You can do the following:
CREATE TABLE SECOND AS (
SELECT ID, NAME AS VALUE
FROM FIRST
WHERE 1 = 2
);
If think the %type syntax is a plsql thing only
In standard SQL, you'd write a CREATE DOMAIN statement.
CREATE DOMAIN my_name_type VARCHAR(25);
But I don't think Oracle supports CREATE DOMAIN, so you I think you need to create an object instead.
create type my_name_type as object
( my_name_col varchar2(25));
In either case, you'd use it directly in creating a table.
create table test (
user_name my_name_type
);
I recall that the syntax for INSERT statements is a little weird; check the docs for that.
You could do this in SQL Server by using SELECT INTO:
SELECT TOP 0 CAST(0 as int) as 'id', Field
INTO NewTable
FROM OtherTable

INSERT, and get the auto-incremented value

Consider the following table:
create table language (
id integer generated always as identity (START WITH 1, INCREMENT BY 1),
name long varchar,
constraint language_pk primary key (id)
);
To which I'd insert an entry this way.
insert into language(name) values ('value');
How does one know what value for id was created? Just doing a SELECT using the name field is not valid, because there can be duplicate entries.
Through plain SQL:
insert into language(name) values ('value');
SELECT IDENTITY_VAL_LOCAL();
See the manual for details: http://db.apache.org/derby/docs/10.7/ref/rrefidentityvallocal.html
When doing this from a Java class (through JDBC) you can use getGeneratedKeys() after "requesting" them with the approriate executeUpdate() method.
You use the JDBC method
st.execute(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet keys = st.getGeneratedKeys();
as documented in the Derby manual.
See also Javadocs: DatabaseMetaData#supportsGetGeneratedKeys()
and Statement#getGeneratedKeys()
You could execute this statement (NB, not 100% sure this syntax is correct for Derby:
SELECT TOP 1 id FROM language ORDER BY id DESC
To find the last inserted ID.
Alternative for Derby:
SELECT MAX(id) from language
Obviously this will only be accurate if no other inserts (including inserts by other users) have happened between your insert and select.
See also this discussion:

iSeries DB2 - Is there any way to select the identity value from an insert statement?

I know we're rare, us poor folk that are using iSeries for DB2/AS400, but I'm hoping someone can answer this simple question. Is there any way to return the identity value from an insert statement without using two lines of SQL? I'm being forced to use inline SQL in C# to perform an insert, and then I need to use the identity generated for the insert for something later on. Simply put, I need the iSeries DB2 equivalent of Oracle's "RETURNING." I.e.,
INSERT INTO AwesomeTable (column1, column2, etc.)
VALUES (value1, value2, etc.)
RETURNING something;
Anyone? Thanks in advance.
EDIT: Unless someone knows of a way I can execute two lines of SQL in one IBM.Data.DB2.iSeries.iDB2Command (not a stored proc), I would like to do this all in one line of SQL
I am not sure of iSeries, but the following worked on db2v8.1:
Consider 'ID' is the name of your identity column. The following stmt will return the newly generated id (the same one that gets inserted by the insert stmt):
SELECT ID FROM FINAL TABLE (
INSERT INTO AwesomeTable (column1, column2, etc.)
VALUES (value1, value2, etc.)
)
Some explanation I found on the publib site: (I used it for reference to test my query above)
/* The following SELECT statement references an INSERT statement in its
FROM clause. It inserts an employee record from host variables into
table company_b. The current employee ID from the cursor is selected
into the host variable new_id. The keywords FROM FINAL TABLE
determine that the value in new_id is the value of ID after the
INSERT statement is complete.
Note that the ID column in table company_b is generated and without
the SELECT statement an additional query would have to be made in
order to retreive the employee's ID number.
*/
EXEC SQL SELECT ID INTO :new_id
FROM FINAL TABLE(INSERT INTO company_b
VALUES(default, :name, :department, :job, :years, :salary,
:benefits, :id));
Hope this helps :)
You need to use the IDENTITY_VAL_LOCAL scalar function. From the IBM documentation:
IDENTITY_VAL_LOCAL is a
non-deterministic function that
returns the most recently assigned
value for an identity column.
Example:
CREATE TABLE EMPLOYEE
(EMPNO INTEGER GENERATED ALWAYS AS IDENTITY,
NAME CHAR(30),
SALARY DECIMAL(5,2),
DEPT SMALLINT)
INSERT INTO EMPLOYEE
(NAME, SALARY, DEPTNO)
VALUES('Rupert', 989.99, 50)
SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
Here's an example :
CREATE TABLE AUTOINC (
AUTO91 INTEGER GENERATED ALWAYS AS IDENTITY,
SCDS91 CHAR(35) NOT NULL DEFAULT '',
MCLD91 DECIMAL(3,0) NOT NULL DEFAULT 0,
CONSTRAINT PK_AUTOINC PRIMARY KEY(AUTO91));
// Notice the default keyword where the auto increment field is.
insert into AUTOINC Values( default ,'SYSC' , 0 )
// And using the function to return the last identity column value.
// Note: fetch first row only.
select **IDENTITY_VAL_LOCAL**() from AUTOINC **fetch first row only**