SQL Using max value from a table as the starting number in an Identity column - identity

This is a stupid question, but here it goes. I need to use the result of the first query as the
starting number in an Identity column. I don't want to do it manually each time.
SELECT MAX([VM_KEY]) + 1 as VM_KEY FROM [DB1].[dbo].[Table1] --30474373
CREATE TABLE [dbo].[table2](
[Segment_Name] [varchar](8) NULL,
[Segment_Name_Flag] [varchar](38) NULL,
[Counter] [int] NULL,
[VM_KEY] [int] IDENTITY(30474373,1) NOT NULL)
Any help would be appreciated.

Related

Query takes more than two seconds

I have a query that takes over 2 seconds.
Here is my table schema:
CREATE TABLE `vouchers` (
`id` int(11) NOT NULL,
`voucher_dealer` int(11) NOT NULL,
`voucher_number` varchar(20) NOT NULL,
`voucher_customer_id` int(11) NOT NULL,
`voucher_date` date NOT NULL,
`voucher_added_date` datetime NOT NULL,
`voucher_type` int(11) NOT NULL,
`voucher_amount` double NOT NULL,
`voucher_last_debt` double NOT NULL,
`voucher_total_debt` double NOT NULL,
`voucher_pay_method` int(11) NOT NULL,
`voucher_note` text NOT NULL,
`voucher_inserter` int(11) NOT NULL
)
The primary key is id and is auto incremented.
The table has more than 1 million rows.
The query looks like this:
select *
from vouchers
where voucher_customer_id = **
and voucher_date between date and date
and sometimes it looks like this:
select sum(voucher_amount)
from vouchers
where voucher_customer_id=**
and voucher_date> date limit 1
Is there a way to speed up my queries?
You'll want to use MySQLs "EXPLAIN" to determine what's going on and why.
http://dev.mysql.com/doc/refman/5.7/en/explain.html
To do so, simply add "EXPLAIN " prior to your statement like this:
EXPLAIN select *
from vouchers
where voucher_customer_id = **
and voucher_date between date and date
It will give you information about available keys, how many rows it's needing to search...etc etc.
You can use that information to determine why it's running slow and how you can improve it's speed.
Once you've run it, you can use any of the many online resources that explain (no pun intended) how to use the "EXPLAIN" results. Here are some:
http://www.sitepoint.com/using-explain-to-write-better-mysql-queries/
How to optimise MySQL queries based on EXPLAIN plan
https://www.digitalocean.com/community/tutorials/how-to-optimize-queries-and-tables-in-mysql-and-mariadb-on-a-vps
Create another index for voucher_date

Resolving "Arithmetic overflow error converting varchar to data type numeric" in SQL for insert statement

I want to create a SQL table with the following column datatypes.
Name : Varchar
Grade : Data will have “#” followed by numbers and also can be varchar. Eg : #1, #2, TML
Sizes : Can be whole numbers and fractions. Eg: 26/30, 80, 85/69
Average : Will be decimal numbers.
I have created table based on the above requirements:
CREATE TABLE [dbo].[Report_Proj](
[Name] [nvarchar](255) NOT NULL,
[Grade] [nvarchar](50) NOT NULL,
[Sizes] [float](10) NOT NULL,
[Average][decimal](10, 10) NOT NULL
But when I insert data into this table I’m getting the error “Msg 8115, Level 16, State 8, Line 1
Arithmetic overflow error converting varchar to data type numeric.
The statement has been terminated.”
Where could I possibly be going wrong.
Need the above data for reporting purposes and will not have any arithematic calculations in future.
just change the decimal value data type to (10,2)
declare #Report_Proj TABLE (
[Name] [nvarchar](255) NOT NULL,
[Grade] [nvarchar](50) NOT NULL,
[Sizes] [float](10) NOT NULL,
[Average][decimal](18, 2) NOT NULL)
insert into #Report_Proj ([Name],[Grade],[Sizes],[Average])values ('ram','#1',26/30,10.2)
select * from #Report_Proj

Adding records from two SQL Server tables that are unique on one column

I have two tables in a SQL Server database, one containing letters that are posted and one of documents that are sent electronically.
CREATE TABLE [dbo].[DocumentTransmission]
(
[PatientNumber] [varchar](50) NULL,
[Filename] [varchar](512) NOT NULL,
[TransmittedDateTime] [datetime2](3) NULL,
[GPCode] [varchar](50) NULL,
[PracticeCode] [varchar](50) NULL,
[MessageSource] [varchar](50) NULL,
[Status] [varchar](50) NULL,
[EmailAddress] [varchar](64) NULL,
[DateTimeAdded] [datetime2](3) NULL
) ON [PRIMARY]
The other table is called DocumentPrint
I need to be able to select records from DocumentTransmission and only those from DocumentPrint where the Filename does NOT appear in DocumentTransmission - and I can't seem to figure out how to do this quickly - the routine I have would make a DBA cry as it is so slow - how would you recommend this is done.
There is no adding records in SQL. However, you can merge two (or more) SELECT results together with an UNION. Something like :
SELECT * FROM DocumentTransmission UNION SELECT * FROM DocumentPrint
Since you also want to exclude rows from the second query you have to add a condition :
SELECT * FROM DocumentTransmission UNION SELECT * FROM DocumentPrint WHERE Filename NOT IN (SELECT FileName FROM DocumentTransmission)
But don't expect this query to be very fast : you are comparing two very long VARCHAR columns and this is going to be slow if you have many rows in your table.

How to create index in SQL to increase performance

I have around 200,000 rows in database table. When I execute my search query, it's taking around 4-5 seconds to give me results in next page. I want that execution should be fast and results should be loaded under 2 seconds. I have around 16 columns in my table.
Following is my query for creation of table
Create table xml(
PID int not null,
Percentdisc int not null,
name varchar(100) not null,
brand varchar(30) not null,
store varchar(30) not null,
price int not null,
category varchar(20) not null,
url1 varchar(300) not null,
emavail varchar(100) not null,
dtime varchar(100) not null,
stock varchar(30) not null,
description varchar(200) not null,
avail varchar(20) not null,
tags varchar(30) not null,
dprice int not null,
url2 varchar(300),
url3 varchar(300),
sid int primary key auto_increment);
Select query which I'm using
select * from feed where (name like '%Baby%' And NAME like '%Bassinet%')
I dont have much knowledge of indexing the database, to increase performance. Please guide me what index to use.
Indexes aren't going to help. LIKE is a non sargable operator. http://en.wikipedia.org/wiki/Sargable
The wildcard opeartor % used in starting of matching string renders any index created useless .
More are the characters before 1st wildcard operator , faster is the index lookup scan .
Anyways you can add an index to existing table
ALTER TABLE feed ADD INDEX (NAME);
This will have no index usage even after creating index on NAME column becuse it has a leading % character
select * from feed where (name like '%Baby%' And NAME like '%Bassinet%')
This will use indexing as starting % removed
select * from feed where (name like 'Baby%' And NAME like 'Bassinet%')
There's a good read here.
LIKE does not use the full text indexing. If you want to use full text searching you can use MySQL full text search functions, You can read MySQL doc regarding this.
Here's the syntax for adding INDEX in MySQL:
ALTER TABLE `feed`
ADD INDEX (`Name`);
MySQL Match example:
Substring matches: (Matches: Babylonian, Bassineete etc.)
SELECT * FROM `feed` WHERE MATCH (NAME) AGAINST ("+Baby* +Bassinett*" IN BOOLEAN MODE);
Exact matches:
SELECT * FROM `feed` WHERE MATCH (NAME) AGAINST ("+Baby +Bassinett" IN BOOLEAN MODE);
In your case index is not usefull. When we find with like operator it not use index. When we direct search i.e columnname = 'Ajay', at this time it search in index(if apply). The reason is index is searching with the physical data ,not with logical data(for like operator).
You can use Full-text search for this where you can define only those column in which you need to find data. FTS is usefull and get faster data when more data as you have.
How to enable FTS, please check the link.
http://blog.sqlauthority.com/2008/09/05/sql-server-creating-full-text-catalog-and-index/

Generating Unique Usernames in SQL Server

I am curious how people are handling the following situation. Let's say we have a Users Table that looks something like this:
CREATE TABLE [dbo].[Users](
[UserId] [uniqueidentifier] NOT NULL,
[ProfileId] [uniqueidentifier] NULL,
[UserTypeId] [uniqueidentifier] NOT NULL,
[UserName] [varchar](150) NOT NULL,
[Password] [varchar](150) NOT NULL,
[Salt] [nchar](10) NOT NULL,
[ActivationCode] [char](8) NULL,
[InvalidLoginAttempts] [int] NOT NULL,
[IsLockedOut] [int] NOT NULL,
[LastLoginDate] [datetime2](7) NOT NULL,
[Active] [int] NOT NULL,
[DateCreated] [datetime2](7) NOT NULL,
[LastUpdated] [datetime2](7) NOT NULL,
So here is my actual question. Previously when using int for the PK I could insert a user and autocreate a username based on the identity insert if the user did not supply a username. Example of why this would happen. "OpenId Registration for instance" So how would one generate a unique "count" so to say using guids. I certainly don't want to display "welcome userXXX-XXX-XXX and so on.
My thoughts are maybe build a seperate table for this with and int IDENTITY and store the guid in there??
Why not just add another column with identity to the table and use that.
Or pick a random number, check if userName already exists, if so generate a new.
Following Magnus's proposal, you could build a default user name by concatenating an additional int/autonumber field in the table + the server's name (or the database name), or part of it as!
Suppose that you have SERV1, SERV2, SERV3 running. You could then either build the default user name as userSERVX_Y, or userSERVX0000Y, etc. Your username building scheme will depend on your server naming strategy. If your server names are not 'sexy'enough, you could add somwehere a table with aliases for your servers.