how to function parameter take value automatically in sql server - sql

i have create a table
infobool (
book_id int identity(1,1) primary key,
bid varchar(20),bname varchar(50)
)
now i want use a function
dbo.book_id(#a int)
returns varchar(20)
as
begain
return 'bkid00'+convert(varchar(10),#a)
end
now how this function take automatically value from book_id column

It looks like you are just trying to prepend a value to your book_id column?
You can achieve that without a function, try something like this:
SELECT 'bkid00' + CONVERT(VARCHAR(10, book_id), bid
FROM infobool

Related

Can I insert into multiple related tables in a single statement?

I have two related tables something like this:
CREATE TABLE test.items
(
id INT identity(1,1) PRIMARY KEY,
type VARCHAR(max),
price NUMERIC(6,2)
);
CREATE TABLE test.books
(
id INT PRIMARY KEY REFERENCES test.items(id),
title VARCHAR(max),
author VARCHAR(max)
);
Is it possible to insert into both tables using a single SQL statement?
In PostgreSQL, I can use something like this:
-- PostgreSQL:
WITH item AS (INSERT INTO test.items(type,price) VALUES('book',12.5) RETURNING id)
INSERT INTO test.books(id,title) SELECT id,'Good Omens' FROM item;
but apparently SQL Server limits CTEs to SELECT statements, so that won’t work.
In principle, I could use the OUTPUT clause this way:
-- SQL Server:
INSERT INTO test.items(type, price)
OUTPUT inserted.id, 'Good Omens' INTO test.books(id,title)
VALUES ('book', 12.5);
but this doesn’t work if there’s a foreign key involved, as above.
I know about using variables and procedures, but I wondered whether there is a simple single-statement approach.
You can using dynamic sql as follows. Although its awkward to construct query like this.
CREATE TABLE dbo.items (
id INT identity(1,1) PRIMARY KEY,
type VARCHAR(max),
price NUMERIC(6,2)
);
CREATE TABLE dbo.books (
id INT PRIMARY KEY REFERENCES dbo.items(id),
title VARCHAR(max),
author VARCHAR(max)
);
insert into dbo.books(id,title)
exec ('insert into dbo.items(type,price) output inserted.id,''Good Omen'' VALUES(''book'',12.5)')

Yes/No column in SQL 2018 studio

Can anyone explain how to create a yes/no column in SQL Studio 2018? BOOL or bit(1) are not working.
Create Table Diseases
(
P_ID int not null,
NameofDis varchar(100),
DateofDis date,
Condition bit(1),
);
You can use simple BIT datatype or you can use BOOLEAN data type like this
Create Table Diseases(
P_ID int not null,
NameofDis varchar(100),
DateofDis date,
Condition BIT,
);
or
Create Table Diseases(
P_ID int not null,
NameofDis varchar(100),
DateofDis date,
Condition BOOLEAN,
);
Try using BIT instead of BIT(1). This will create the column as a yes/no field aka true/false field where 1 is yes/true and 0 is no/false.
Your code:
Create Table Diseases(
P_ID int not null,
NameofDis varchar(100),
DateofDis date,
Condition bit
);

Computed column 'BookID' in table 'Books' cannot be persisted because the column is non-deterministic

I want to create a table with computed column for its custom ID column. The format which I want is BID(The Year)-0000 for example the one like this:
BID2017-0001
I tried the below t-sql code but I get the non-deterministic error. How can I solve this problem?
CREATE TABLE Books
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
BookID AS 'BID'+CAST(YEAR(GETDATE()) as VARCHAR(4))+ RIGHT ('0000' + CAST(ID AS VARCHAR(4)), 4) PERSISTED UNIQUE,
ISBN VARCHAR(32),
BookName NVARCHAR(50),
AuthorName NVARCHAR(50),
BLanguage VARCHAR(50),
StaId int,
StuId int,
CatNo int);
I tried this article too but couldn't solve the issue.
non-deterministic
UPDATE
Furthermore, I need the series of '0000' to be reset back to '0000' when the new year starts. For example, The last ID in 2017 is 'BID2017-0932' when the year is changed to 2018 I would like zero series in the ID to be reset to '0000' for example 'BID2018-0001' how can I achieve this ??
Simplest solution
I would add a CreateDate column thus:
ALTER TABLE dbo.Books
ADD CreateDate DATETIME NOT NULL
CONSTRAINT DF_Books_CreateDate
DEFAULT(GETDATE())
GO
then I would add computed column thus:
ALTER TABLE dbo.Books
ADD BookID AS ('BID' + LTRIM(YEAR(CreateDate)) + '-' + RIGHT('0000' + LTRIM(ID), 4)) /*PERSISTED*/
GO
you have getdate() in your code which makes the column non deterministic.Removing that will help ..
If you want to know why getdate() is nondeterministic.check here:Is GetDate() deterministic..
Excerpt from answer
deterministic means that the function returns the same value given the same inputs. In this case you have no inputs, but you get different values all the time! The system clock is not an input, it is external state that the function relies upon.

MSSQL function in check constraint

I would like to create table with CHECK constraint, where CHECK calls an user defined scalar function. I have read on multiple sites that it is possible, also that it has bad performance. Even though I would like to do it.
I have this table
CREATE TABLE [book_history] (
id int NOT NULL IDENTITY PRIMARY KEY,
user_id int NOT NULL,
library_id int NOT NULL,
book_id int NOT NULL,
borrow_time datetime DEFAULT GETDATE(),
return_policy datetime DEFAULT DATEADD(DAY, 30, GETDATE()),
return_time datetime,
CHECK (dbo.fn_check_duplicate(user_id, library_id, book_id) = 0)
);
and function
DROP FUNCTION IF EXISTS fn_check_duplicate
GO
CREATE FUNCTION fn_check_duplicate (#user_id int, #library_id int, #book_id int)
RETURNS int
BEGIN
RETURN (SELECT COUNT(*) FROM [book_history] WHERE user_id = #user_id AND library_id = #library_id AND book_id = #book_id AND return_time IS NULL)
END
GO
When I try to insert new row into this book_history table (which is empty), I get an error saying The INSERT statement conflicted with the CHECK constraint "CK__book_history__267ABA7A". The conflict occurred in database "library", table "dbo.book_history".
COUNT is supposed to return int data type based on MSDN documentation.
I am owner of both, the table and the function.
Can anyone tell me what am I doing wrong?
Change it to check (dbo.fn_check_duplicate(user_id, library_id, book_id) = 1)
The check is going to look at the state of the table after the insert, so you want the count to be 1.
Test it on rextester: http://rextester.com/AWDNP40594 by uncommenting the second insert.
You can also replace this slow check constraint with a filtered unique index like so:
create unique nonclustered index uix_book_history_user_library_book
on dbo.book_history (user_id, library_id, book_id)
where return_time is null
This might be more of what you are trying to do, if each book_id is an individual book:
create unique nonclustered index uix_book_history_library_book
on dbo.book_history (library_id, book_id)
where return_time is null
Because this would allow a book to only be checked out by one user at a time.

CREATE TABLE where multiple columns are inserted with same value

Lets say I have a CREATE TABLE code like this:
CREATE TABLE Test (
ID int NOT NULL IDENTITY(1,1),
SortIndex int,
Name nvarchar(50) NOT NULL
);
I was wondering if it's possible to make a table in MSSQL which had the ability to insert the ID's value into the SortIndex column when I run an INSERT.
So I would run this INSERT:
INSERT INTO Test (Name) VALUES ('Awesome Dude');
Which would normally yield the row:
ID,SortIndex,Name
1,NULL,"Awesome Dude"
But I'd like it to automatically be:
ID,SortIndex,Name
1,1,"Awesome Dude"
Is this even possible by altering the CREATE TABLE script, or do I have to use a TRIGGER?
I would be inclided to take a slightly different approach to this. If you want your SortIndex to default to the ID, but be overridable, I would use a nullable column, and a computed column:
CREATE TABLE Test (
ID int NOT NULL IDENTITY(1,1),
OverrideSortIndex int,
Name nvarchar(50) NOT NULL,
SortIndex AS ISNULL(OverrideSortIndex, ID)
);
If you need to change the sort index for any reason, update the column OverrideSortIndex and this takes precedence.