I'm creating VF tables using C#. The Create Table statement looks like
{CREATE TABLE NMMAIN (
NAMETYPE Character(4),
NAME_ID Numeric(11) AUTOINCREMENT,
RACE Character(2),
RELIGION Character(10),
REPORTAREA Character(8),
RESTRICTNM Numeric(1),
RES_STATUS Character(1),
SEX Character(1),
SKINTONE Character(6),
CONSTRAINT primKey PRIMARY KEY(NAME_ID)
)}
This throws a "Syntax Error" on executing the query. It does work fine if I don't add the Constraint. any help is appreciated.
You are using the wrong syntax. Looking at the CREATE TABLE syntax for Visual Foxpro the correct syntax would be either:
CREATE TABLE NMMAIN (
...,
NAME_ID Numeric(11) AUTOINC PRIMARY KEY,
...
)
Or:
CREATE TABLE NMMAIN (
...,
NAME_ID Numeric(11) AUTOINC,
...,
PRIMARY KEY NAME_ID TAG primKey
)
Note I have used AUTOINC instead of AUTOINCREMENT, as the reference I link to doesn't show AUTOINCREMENT.
Your final problem, I think, is that only the Integer type can use AUTOINC, not Numeric.
Here is the CREATE TABLE clause definition:
CREATE TABLE | DBF Table_Name
[CODEPAGE = nCodePage]
(FieldName1 FieldType [( nFieldWidth [, nPrecision] )] [NULL | NOT NULL]
[AUTOINC [NEXTVALUE NextValue [STEP StepValue]]]
[, FieldName2 ... ] [ ... ] )
And an example:
CREATE TABLE "D:\Data\customer.dbf" (id I AUTOINC NEXTVALUE 1 STEP 1, name C(40), payment F(5,2))
Taken from here.
Related
How can one get before and after insert unique ID from output clause while inserting?
For example: I have a table named A, I need to copy some of the records via
insert into select statement
and I need to get old unique id and new unique id in to a temp table using
OUTPUT Clause
This means I need to get return type as before insert unique identifier and after inert unique identifier. For that, I tried using below query as
DECLARE #MyTableVar TABLE
(
newid UNIQUEIDENTIFIER,
oldid UNIQUEIDENTIFIER
);
INSERT A (name, description)
output inserted.guid,
d.guid
INTO #MyTableVar
SELECT name, description
FROM A d
WHERE deptID = 550;
SELECT *
FROM #MyTableVar
But I am not able to get d.guid in output clause. Please correct me if there are any other options to get before and after insert unique id as output.
You should use column names from table.In your case ,you are using Inserted.Guid which should throw syntax error
create table tt
(
id varchar(300) default newid()
)
declare #t table
(
id varchar(300)
)
insert into tt
output inserted.* into #t
default values
select * from #t
You can use
##IDENTITY
to get after insert unique id as output.
I have the below SQL query using the Query Builder in Visual Studio. As you can see the same user is duplicated 3 times, this is due to the user having 3 different skills. How can I merge the 3 skills together in the SQL query or in a ListView control so that it only displays one result instead of 3 and that the user has their 3 skills listed?
SELECT users.role_id, users.username, users.first_name, users.last_name, users.description, roles.role_id, roles.role, skills.skill_id, skills.user_id, skills.skill
FROM users
INNER JOIN roles ON users.role_id = roles.role_id
INNER JOIN skills ON users.user_id = skills.user_id
WHERE (users.role_id = 3)
Use For XML Path(''), Type. It is a bit of a hack, because you're really creating an XML string without a root and fashioning odd elements, but it works well. Be sure to include the Type bit, otherwise the XML trick will attempt to convert special characters, like < and & into their XML escape sequences (here is an example).
Here is a simplified version of your problem in a SQL Fiddle. Below is the relevant Select snippet.
SELECT users.user_id, users.first_name,
STUFF(
(SELECT ', ' + skill
FROM skills
WHERE users.user_id = skills.user_id
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
, 1, 2, '') AS skill_list
FROM users
Try using Stuff and For Xml
Here's the Fiddle:
http://sqlfiddle.com/#!6/fcf71/5
See if it helps, it's just a sample so you will have to change the column names.
You can use PIVOT on the Skill then group those skills into one column.
To make it simple, I test it with some sample data like the following:
CREATE SCHEMA _Test
CREATE TABLE _Test.SkillSet(SkillId INT IDENTITY(1,1) PRIMARY KEY, SkillName NVARCHAR(64))
INSERT INTO _Test.SkillSet(SkillName) VALUES('C/C++')
INSERT INTO _Test.SkillSet(SkillName) VALUES('C#')
INSERT INTO _Test.SkillSet(SkillName) VALUES('Java')
CREATE TABLE _Test.Employees(EmpId INT IDENTITY(1,1) PRIMARY KEY, FullName NVARCHAR(256))
INSERT INTO _Test.Employees(FullName) VALUES('Philip Hatt')
INSERT INTO _Test.Employees(FullName) VALUES('John Rosh')
CREATE TABLE _Test.Employee_Skill(EmpId INT FOREIGN KEY REFERENCES _Test.Employees(EmpId), SkillId INT FOREIGN KEY REFERENCES _Test.SkillSet(SkillId))
INSERT INTO _Test.Employee_Skill(EmpId, SkillId) VALUES(1, 1)
INSERT INTO _Test.Employee_Skill(EmpId, SkillId) VALUES(1, 2)
INSERT INTO _Test.Employee_Skill(EmpId, SkillId) VALUES(1, 3)
INSERT INTO _Test.Employee_Skill(EmpId, SkillId) VALUES(2, 2)
INSERT INTO _Test.Employee_Skill(EmpId, SkillId) VALUES(2, 3)
WITH tEmpSkill
AS
(SELECT A.EmpId, A.FullName, C.SkillName
FROM _Test.SkillSet C RIGHT JOIN
(
_Test.Employees A LEFT JOIN _Test.Employee_Skill B
ON A.EmpId = B.EmpId
)
ON B.SkillId = C.SkillId
)
SELECT * FROM tEmpSkill
PIVOT(COUNT(SkillName) FOR SkillName IN([C/C++], [C#], [Java])) AS Competency
The query above gives me an intermediate result
PIVOT RESULT
Now you can easily make a string containing all the skills needed for each employee. You can also search for some articles to use the PIVOT with unknown number of columns (skill sets), which may better serve your need.
Hope this can help.
I'm pretty new to databases and sql. I have a problem where I have two tables which both contain a foreign key to the primary key of the other. My problem is I have a large number of elements which can have multiple names in different languages, but MUST have a single primary name/language.
alt text http://img688.imageshack.us/img688/1121/11768540.png
Firstly, I want to know if this is possible, or should I just give up already? The obvious solution is to have an extra boolean field in the ElementName table to say IsDefaultName, but it adds some extra complexity for querying and updating. If this is the best solution, how do I constrain the ElementName table to not accept any submission if IsDefaultName is set and the table already has an entry with the same ElementId and IsDefaultName set (or would I need to query this manually)?
I'm attempting to use LINQ to SQL here. The code I'm using to attempt to insert new items throws an exception at SubmitChanges with The INSERT statement conflicted with the FOREIGN KEY constraint "FK_ElementName_Element". I can understand why this is, but wondering if there's a fix/better solution.
var db = new MyDBDataContext();
var element = new Element();
var elementName = new ElementName() {
ElementName1 = "MyElement",
Language = "English",
};
element.ElementName = elementName;
db.Elements.InsertOnSubmit(element);
db.ElementNames.InsertOnSubmit(elementName);
db.SubmitChanges();
Solution 1
element
------------------
element_id
~....
element_name
------------------
element_name_id
fk_element_id
name
language_id
is_default_name Default ( 0 )
Trigger:
if ( ( select count ( 1 ) from element_name where is_default_name = 1 ) > 1 )
BEGIN
raisError ( 'only 1 element_name may be marked is_default_name = true.', 16, 1 );
END
Solution 2
element
------------------
element_id ( pk )
~....
element_name
------------------
element_name_id ( pk )
fk_element_id
name
language_id
element_name_default
------------------
fk_element_id
fk_element_name_id
( pk - fk_element_id, fk_element_name_id )
Solution 3
element
------------------
element_id
fk_element_name_id_default NULL
~....
element_name
------------------
element_name_id
fk_element_id
name
language_id
order of code:
* Insert to element_name
* update of element
I would stick with what you had, cause it is just fine, just:
db.Elements.InsertOnSubmit(element);
db.ElementNames.InsertOnSubmit(elementName);
//I don't know this syntax to say
// set the property of element.fk_element_name_id_default
// to the newly inserted elementName from above
db.Elements.?.?
Why not simply use a self-join like so:
Create Table Elements(
ElementId... Not Null Primary Key
, DefaultElementId ... Not Null
References Elements( ElementId )
, Name ...
, Language ...
)
The default name is the one where ElementId = DefaultElementId.
Btw, this is a place where a guid PK is nicer than an identity column. With a guid PK, you could generate both the ElementId and DefaultElementId from the client. If you are using an identity column with this schema, you'll probably have to create a "Unknown" elementId with a known value like zero so that you can do the insert and then turn around and do an update all in a single transaction.
** ADDITION **
Given what you said in comments, it sounds like you are trying to localize the elements data. My inclination would be to recommend adding a non-nullable "Name" column to the Elements table which represents the language neutral or default language name. Your ElementNames table would have a foreign key to the Elements table and would only populate that table when you localized an element name. Your queries would then need to coalesce on the requested language name and the name in the elements table if the requested language did not have a localized name.
I have a SqlQuery that looks like this:
SqlQuery query =
DB.Select(
Order.Schema.TableName + ".*",
OrderDetail.Schema.TableName + ".*")
.From<Order>()
.InnerJoin<OrderDetail>()
.Where(Order.IdColumn).IsEqualTo(1);
Now I would expect the Method SqlQuery.ExecuteJoindDataSet() to generate a DataSet for me, that contains 2 DataTables (one for Orders, one for OrderDetails) and put a DataRelation into the DataSet, so I don't have to do this all by hand.
But ExecuteJoinedDataSet() only generates one Table containing all the data from Order but not from OrderDetail:
// Order = 104 Columns
// OrderDetail = 74 Columns
query.ExecuteJoinedDataSet().Tables.Count => 1
query.ExecuteJoinedDataSet().Tables[0].Columns.Count => 104
query.ExecuteDataSet().Tables[0].Columns.Count => 177
I think I am on the right way, but can someone please tell me, what I am doing wrong?
The purpose of this is that the Printing Component I use in my project does not accept generic objects, but DataSet's as a DataSource.
ExecuteJoinedDataSet actually uses all the table columns from the first table and replaces the value in any column that has a foreign key with the first non-forgeign-key value from the corresponding row in the foreign table. It does inner joins for non-null foreign-key columns, and left joins for nullable ones.
So for this schema
create table tblBaseType
(
id int not null primary key identity(1,1),
name not null varchar(100) unique
)
create table tblBaseLocation
(
id int not null primary key identity(1,1),
name not null varchar(100) unique
)
create table tblBase
(
id int not null primary key identity(1,1),
name varchar(100) not null unique,
baseTypeID int not null references tblBaseType(id),
baseLocationID int null references tblBaseLocation(id)
)
and a SqlQuery like
SqlQuery q = new Select().From(TblBase.Schema).Where(TblBase.IdColumn).IsEqualTo(1);
DataSet ds = q.ExecuteJoinedDataSet();
this approximate sql would be generated:
select tblBase.Id,
tblBase.Name,
tblBaseType.Name as baseTypeId,
tblBaseLocation.name as baseLocationId
from tblBase
inner join tblBaseType on tblBase.baseTypeID = tblBaseType.id
left join tblBaseLocation on tblBase.baseLocationID = tblBaseLocation.id
The actual sql is fully qualified, this is just a rough from-scratch approximation.
I have been looking into Fluent Nhibernate, and it seems really promising. But...
I can't seem to get it working with a MySQL database. I have the Fluent Nhibernate example project running fine with the SQLite database (Fluent NHibernate: Getting Started), but as soon as I change the database configuration to this:
return Fluently.Configure()
.Database(MySQLConfiguration.Standard.ConnectionString(
x => x.Database("database")
.Server("server")
.Username("login")
.Password("password")
)
)
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<Program>())
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory();
I get a strange exception:
Value cannot be null. Parameter name: stream
I know that I can connect to the MySQL with a simple SQL statement from the same project.
Any ideas? :)
Unfortunatly I canĀ“t tell you why but it seems to be an issue with the MySql connector.
Add this:
.ExposeConfiguration(c => c.Properties.Add("hbm2ddl.keywords", "none"));
to your configuration and see if it helps. I found the solution at the hibernate forums.
Does your schema exist? Because your using .ExposeConfiguration(BuildSchema) to "build" it?
I had the same problem and finally I figured it out.
First you need to set a database with the tables used in the example. See script below. (I omitted the Location object).
Then I used the following CreateSessionFactory code:
var cfg = MySQLConfiguration
.Standard
.ShowSql()
.UseOuterJoin()
.ConnectionString("Server=localhost;Port=3306;Database=testdb;Uid=USER;Password=PASSWORD;use procedure bodies=false;charset=utf8")
.Driver<NHibernate.Driver.MySqlDataDriver>()
;
return Fluently.Configure()
.Database(cfg)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>())
.BuildSessionFactory()
;
Create BD and table script:
DROP DATABASE IF EXISTS testdb;
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE Employee
(
id int not null primary key auto_increment,
FirstName TEXT,
LastName TEXT,
Store_id int(10)
);
CREATE TABLE Product
(
id int not null primary key auto_increment,
Name TEXT,
Price DOUBLE
);
CREATE TABLE Store
(
id int not null primary key auto_increment,
Name TEXT
);
CREATE TABLE StoreProduct
(
Store_id int(10) DEFAULT '0' NOT NULL,
Product_id int(10) DEFAULT '0' not null,
PRIMARY KEY (Store_id, Product_id)
);
SELECT 'Employee table' as '';
desc Employee;
SELECT 'Product table' as '';
desc Product;
SELECT 'Store table' as '';
desc Store;
SELECT 'shopgroup_member table' as '';
desc StoreProduct;