Unable to create a table in SQL - sql

I am trying to execute this simple query.
create Table test1
{
ID int identity(1,1),
value nvarchar
}
Its throwing an error as
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '{'
I am stuck here. Please help me out of this

Use () instead of {}
create Table test1
(
ID int identity(1,1),
value nvarchar
)

don't use follow brace. you should use parenthesis.
create Table test1
(
ID int identity(1,1),
value nvarchar
)
Syntax for create table:
CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);

Use parenthesis ( ) instead of curly braces { }
Set data size for the nvarchar. other wise when insert any string value more than 1 character you will receive String or binary data would be truncated. error
Not mandatory but adding NOT NULL to the IDENTITY column is good practice.
Adding schema name to the table is good practice. (By default dbo is the schema)
So the working query will be:
create Table dbo.test1
(
ID int identity (1, 1) NOT NULL,
value nvarchar (500)
)

Use () instead of {}
Check out this link for the example SQL Create Table
On the internet about the topic you will find many useful information.

Related

SQL invalid column name Site.LocationLat,

CREATE TABLE #Data(
[LocationLat] float NULL,
[LocationLong] float NULL,
[LocationHeight] float NULL,
When I am creating table and insert data that time error occurs.
Invalid Column name.
INSERT INTO #Data
SELECT #ServerName,
Site.LocationLat, /*Error occur invalid column name */
Site.LocationLong, /*Error occur invalid column name */
Site.LocationHeight, /*Error occur invalid column name */
If you are using SQL server try to wrap your column names with [].
INSERT INTO #Data
SELECT #ServerName, [Site.LocationLat], [Site.LocationLong], [Site.LocationHeight]
Site doesn't mean anything without a FROM clause. Perhaps you intend something like this:
CREATE TABLE #Data (
SiteName varchar(255),
[LocationLat] float NULL,
[LocationLong] float NULL,
[LocationHeight] float NULL
);
INSERT INTO #Data (SiteName, LocationLat, LocationLong, LocationLong)
SELECT #ServerName, s.LocationLat, s.LocationLong, s.LocationHeight,
FROM Site s;
This assumes you have a table called Site with the appropriate columns.
Please try out the following code
CREATE TABLE #Data (
SiteName varchar(255),
[LocationLat] float NULL,
[LocationLong] float NULL,
[LocationHeight] float NULL );
**
INSERT INTO #Data (SiteName, LocationLat, LocationLong,
LocationHeight)
SELECT ##ServerName, s.LocationLat, s.LocationLong, s.LocationHeight,
FROM Site s;
**
The problem is not with your #Data table it's your Site table. So we really need to see the definition for that. I suspect it doesn't have a LocationLat column.

Conversion failed when converting the varchar value '0%' to data type int

I'm facing a problem with SQL Server.
I've created a table like this:
create table Components
(
pk BIGINT NOT NULL PRIMARY KEY IDENTITY,
id VARCHAR(50),
descr VARCHAR(50),
in_m INT,
in_iy INT,
p_fw VARCHAR(5000)
);
and I'm trying to insert a couple of values:
insert into Components (id, descr, in_m, in_iy, p_fw)
values ('FW000_A', '0%', 0, 0, '[0.0,0.0,0.0]'),
('FW000_B', '1%', 1, 1, '[1.0,1.0,1.0]');
I get the following error:
Msg 245, Level 16, State 1, Line 111
Conversion failed when converting the varchar value '0%' to data type int.
even though the column descr is correctly defined as varchar(50).
Can anybody help me please? Why is SQL Server trying to convert my strings to int values?
What's missing from your question is that you have more than just the two values lines you've shown, and one of the other ones has an integer literal for the descr column, rather than a string.
This example produces the same error:
declare #t table (Descr varchar(50) not null)
insert into #t(Descr) values
('0%'),
(12)
What I believe happens is that SQL Server first tries to determine the data types for all columns in the values clause. Using data type precedence rules, it observes a varchar literal in one row and an int literal in the other, and so determines that the overall type for this column is int and attempts to perform the conversion that leads to the error.
During this process, it does not use any information about the target table into which the values are going to be placed, including the data types of the columns there.
run this and verify the data types;
sp_columns Components
Looks like 'descr' is really an integer

SQL Table Variables - adding constraint that checks for existence of matching row set

Updating with pmbAustin's suggestion
pmbAustin, thanks. I think that will work. I've created a function "dbo.CK_WinteamSportExists" that returns a 0 or 1. However I'm now getting a baffling error message. When I tested my solution I get the following:
create table #check
(
SportID int
,WinTeamID int
,LoseTeamID int
,check
(
(dbo.CK_WinteamSportExists (WinTeamID , SportID) = 1)
)
)
Error Message:
Msg 4121, Level 16, State 1, Line 1
Cannot find either column "dbo" or the user-defined function or aggregate "dbo.CK_WinteamSportExists", or the name is ambiguous.
I tried using a fully qualified name "mydatabase.dbo.CK_WinteamSportExists", no dice.
It appears that I've got the syntax wrong in the check, but for the life of me I can't find the error.
Original Question
I am trying to enforce referential integrity on a table variable. I'm working in SQL Server 2012.
declare #GameID_Table table (
GameID int
,SportID int
,WinTeamID int
,LoseTeamID int
)
Combinations of WinTeamID/SportID and LoseTeamID/SportID in #GameID_Table must be constrained by the existence of a matching row in a separate table Link_TeamSport defined as:
create table Link_TeamSport
(
TeamID int,
SportID int
primary key (TeamID, SportID)
)
Normally I'd do this with a composite foreign key, however these are not allowed in table variables.
I also tried creating user-defined functions that check for the existence of a matching row in Link_TeamSport, but UDFs are not allowed in table variables either.
Here is an example of working code that illustrates my constraint condition. The code below returns a result of 1 if a matching row is found and 0 if not. However, I cannot figure out how to incorporate this concept into the check constraint within #GameID_Table.
declare #winteam int
declare #sportid int
set #winteam = 1001
set #sportid = 4001
select count(*) from
(
select lts.TeamID, lts.sportid from Link_TeamSport lts
where
(#winteam = lts.TeamID and #sportid = lts.sportid)
) a
Use a #TempTable instead. #TableVariables have a lot of restrictions that #TempTables don't, and also don't perform as well if you're going to have more than just a few rows in them.

String or binary data would be truncated. The statement has been terminated

I have met some problem with the SQL server, this is the function I created:
ALTER FUNCTION [dbo].[testing1](#price int)
RETURNS #trackingItems1 TABLE (
item nvarchar NULL,
warehouse nvarchar NULL,
price int NULL
)
AS
BEGIN
INSERT INTO #trackingItems1(item, warehouse, price)
SELECT ta.item, ta.warehouse, ta.price
FROM stock ta
WHERE ta.price >= #price;
RETURN;
END;
When I write a query to use that function like the following it getting the error
String or binary data would be truncated. The statement has been terminated
How can I fix this problem?
select * from testing1(2)
This is the way I create the table
CREATE TABLE stock(item nvarchar(50) NULL,
warehouse nvarchar(50) NULL,
price int NULL);
When you define varchar etc without a length, the default is 1.
When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.
So, if you expect 400 bytes in the #trackingItems1 column from stock, use nvarchar(400).
Otherwise, you are trying to fit >1 character into nvarchar(1) = fail
As a comment, this is bad use of table value function too because it is "multi statement". It can be written like this and it will run better
ALTER FUNCTION [dbo].[testing1](#price int)
RETURNS
AS
SELECT ta.item, ta.warehouse, ta.price
FROM stock ta
WHERE ta.price >= #price;
Of course, you could just use a normal SELECT statement..
The maximal length of the target column is shorter than the value you try to insert.
Rightclick the table in SQL manager and go to 'Design' to visualize your table structure and column definitions.
Edit:
Try to set a length on your nvarchar inserts thats the same or shorter than whats defined in your table.
In my case, I was getting this error because my table had
varchar(50)
but I was injecting 67 character long string, which resulted in thi error. Changing it to
varchar(255)
fixed the problem.
Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION
#trackingItems1 TABLE (
item nvarchar(25) NULL, -- 25 OR equal size of your item column
warehouse nvarchar(25) NULL, -- same as above
price int NULL
)
Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated
SQL Server 2016 SP2 CU6 and SQL Server 2017 CU12
introduced trace flag 460 in order to return the details of truncation warnings.
You can enable it at the query level or at the server level.
Query level
INSERT INTO dbo.TEST (ColumnTest)
VALUES (‘Test truncation warnings’)
OPTION (QUERYTRACEON 460);
GO
Server Level
DBCC TRACEON(460, -1);
GO
From SQL Server 2019 you can enable it at database level:
ALTER DATABASE SCOPED CONFIGURATION
SET VERBOSE_TRUNCATION_WARNINGS = ON;
The old output message is:
Msg 8152, Level 16, State 30, Line 13
String or binary data would be truncated.
The statement has been terminated.
The new output message is:
Msg 2628, Level 16, State 1, Line 30
String or binary data would be truncated in table 'DbTest.dbo.TEST', column 'ColumnTest'. Truncated value: ‘Test truncation warnings‘'.
In a future SQL Server 2019 release, message 2628 will replace message 8152 by default.

SQL Server 2012 sequence

I create a table and sequence in order to replace identity in the table I use SQL Server 2012 Express but I get this error while I tried to insert data to the table
Msg 11719, Level 15, State 1, Line 2
NEXT VALUE FOR function is not allowed in check constraints, default objects, computed columns,
views, user-defined functions, user-defined aggregates, user-defined
table types, sub-queries, common table expressions, or derived
tables.
T-SQL code:
insert into Job_Update_Log(log_id, update_reason, jobid)
values((select next value for Job_Log_Update_SEQ),'grammer fixing',39);
This is my table:
create table Job_Update_Log
(
log_id int primary key ,
update_reason nvarchar(100) ,
update_date date default getdate(),
jobid bigint not null,
foreign key(jobid) references jobslist(jobid)
);
and this is my sequence:
CREATE SEQUENCE [dbo].[Job_Log_Update_SEQ]
AS [int]
START WITH 1
INCREMENT BY 1
NO CACHE
GO
Just get rid of the subselect in the VALUES section, like this:
insert into Job_Update_Log(log_id,update_reason,jobid)
values (next value for Job_Log_Update_SEQ,'grammer fixing',39);
Reference: http://msdn.microsoft.com/en-us/library/hh272694%28v=vs.103%29.aspx
Your insert syntax appears to be wrong. You are attempting to use a SELECT statement inside of the VALUES section of your query. If you want to use SELECT then you will use:
insert into Job_Update_Log(log_id,update_reason,jobid)
select next value for Job_Log_Update_SEQ,'grammer fixing',39;
See SQL Fiddle with Demo
I changed the syntax from INSERT INTO VALUES to INSERT INTO ... SELECT. I used this because you are selecting the next value of the sequence.
However, if you want to use the INSERT INTO.. VALUES, you will have to remove the SELECT from the query:
insert into Job_Update_Log(log_id,update_reason,jobid)
values(next value for Job_Log_Update_SEQ,'grammer fixing',39);
See SQL Fiddle with Demo
Both of these will INSERT the record into the table.
Try this one:
–With a table
create sequence idsequence
start with 1 increment by 3
create table Products_ext
(
id int,
Name varchar(50)
);
INSERT dbo.Products_ext (Id, Name)
VALUES (NEXT VALUE FOR dbo.idsequence, ‘ProductItem’);
select * from Products_ext;
/* If you run the above statement two types, you will get the following:-
1 ProductItem
4 ProductItem
*/
drop table Products_ext;
drop sequence idsequence;
------------------------------