display columns from different tables during data bind - asp.net

How to bind data from two tables.
tbl_user
first name userid
tbl_usermessage
userid timereceived msgid
How to display username and timereceived in datagrid
SELECT TimeReceived, FirstName FROM tbl_usermessage INNER JOIN tbl_user on tbl_usermessage.tbl_user_UserID = tbl_user.UserID WHERE tbl_message_MsgID = #Value1";
This is what I am trying i am getting syntax error. here Time received is from tbl_usermessage and firstname is from tbl_User and both table has userid

How about joining both tables on your sql query?

You need to connect a SqlDataSource to your DataGrid by setting the SqlDataSource's DataSourceID property to the SqlDataSourceID. Set the SqlDataSource's SelectCommand property to the SQL required to get the items:
SelectCommand="SELECT tableone.username, tableone.userid, tabletwo.userid, tabletwo.timereceived
FROM tableone INNER JOIN tabletwo ON tableone.userid=tabletwo.userid"
And also set the ConnectionString property:
ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>" >

You need to retrieve the data from your database with a SQL Query which JOINs the two tables on a column that is common to both:
Something along these lines:
SELECT
userId, username, timereceived
FROM
Table1 INNER JOIN Table2 ON Table1.userId = Table2.UserID
Here's an example for your reference.

Related

SqlDataSource not Working

Select pmtblempreg.Id
,pmtblempreg.Name
,pmtblempreg.UserName
,pmtbldesignation.Designation
, pmtblempreg.skypeid
,pmtblempreg.EmailId
From pmtbldesignation
Right join pmtblempreg ON
pmtbldesignation.Id = pmtblempreg.DesignationId
This query works fine in oracle database. But when executing using sqlDataSource for populating a gridview an error is showing that invalid table name
when i execute it through the query builder of sqldataSource the query changes to
SELECT PMTBLEMPREG.ID
,PMTBLEMPREG.NAME
,PMTBLEMPREG.USERNAME
,PMTBLDESIGNATION.DESIGNATION
,PMTBLEMPREG.SKYPEID
,PMTBLEMPREG.EMAILID
FROM { **oj PMTBLDESIGNATION**
RIGHT OUTER JOIN PMTBLEMPREG ON
PMTBLDESIGNATION.ID = PMTBLEMPREG.DESIGNATIONID
}
an oj is automatically created along with the table name.
Is that the problem??
Try like this
Just Use this code in CodeBehid
Dim SQLStatement As String = "Select pmtblempreg.Id,pmtblempreg.Name,pmtblempreg.UserName ,pmtbldesignation.Designation, pmtblempreg.skypeid,pmtblempreg.EmailId From pmtbldesignation
Right join pmtblempreg ON pmtbldesignation.Id = pmtblempreg.DesignationId"
sqldatsrc.ConnectionString = ConnectionString
sqldatsrc.SelectCommand = SQLStatement
Or Paste the query in SQLDatasource Select Command as
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=xx;User ID=xx;Password=xxx" ProviderName="xx" SelectCommand="Select pmtblempreg.Id,pmtblempreg.Name,pmtblempreg.UserName ,pmtbldesignation.Designation, pmtblempreg.skypeid,pmtblempreg.EmailId From pmtbldesignation
Right join pmtblempreg ON pmtbldesignation.Id = pmtblempreg.DesignationId"></asp:SqlDataSource>
SELECT PE.ID
,PE.NAME
,PE.USERNAME
,PD.DESIGNATION
,PE.SKYPEID
,PE.EMAILID
FROM PMTBLDESIGNATION PD
RIGHT OUTER JOIN PMTBLEMPREG PE ON
PD.ID = PE.DESIGNATIONID
where PD is the Table name alias for PMTBLDESIGNATION and PE is the Table name alias for PMTBLEMPREG
Updated:
By default if you execute the query it checks the table in the Master Database
Instead before executing query Write this code
Use Your_database_name
The database name is where the tables are placed.
Try this
Hope this Helps

Giving alias in JOIN command in sqldatasource

I am using JOIN command to connect two tables in SqlDataSource.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:CS %>"
SelectCommand="SELECT UserName as UN, AboutMe, WebPage, Email FROM Users JOIN ProfileImages ON ProfileImages.UserName = Users.UN WHERE (UN = #UserName)" >
</asp:SqlDataSource>
In MS SQL Server Management Studio this command is ok. But in the SqlDataSource it return errors - Invalid column name 'UN', Ambiguous column name 'UserName'
How do I alias this command right in SqlDataSource to not return these errors?
Your query is a bit wrong
You used alias i a wrong way
First:
You can use alias in the following sections:
Fields. Example Username as UN
Tables names: UserTable as US
In the order by section example: Order BY UN Desc
This because the sql runs the query operations in the following sequence:
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
So because the FROM clause runs first the sql doesn't know about the alias in the SELECT clause
Take a look on a correct query
SELECT
UserName as UN,
AboutMe,
WebPage,
Email
FROM Users
JOIN ProfileImages ON ProfileImages.UserName = Users.UserName
WHERE (Users.UserName = #UserName)
I'm not an expert at SQL, but if both ProfileImages and Users contain the column 'UserName', then in your select columns you need to specify the table from which the UserName is pulled. So something like:
SELECT Users.UserName as UN, Users.AboutMe, Users.WebPage, Users.Email
FROM Users
JOIN ProfileImages ON ProfileImages.UserName = Users.UserName
WHERE (Users.UserName = #UserName)
You cannot use the column alias in the where clause.
SELECT UserName as UN, AboutMe, WebPage, Email
FROM Users usersAlias JOIN ProfileImages piAlias ON piAlias.UserName = usersAlias.UserName
WHERE (usersAlias.UserName = #UserName)
It makes sense when you look at the order of execution:
http://blog.sqlauthority.com/2009/04/06/sql-server-logical-query-processing-phases-order-of-statement-execution/
Since the order of execution is:
These phases and their orders are given as follows:
FROM
ON
OUTER
WHERE
GROUP BY
CUBE | ROLLUP
HAVING
SELECT
DISTINCT
10 ORDER BY
TOP
When these are being processed (the "from" (#1) and "on" (#2) and "where" (#4))..they have no knowledge about the "select" (#8) (aka, the alias name for UN), the column alias in the select clause cannot be used in the WHERE and FROM (and ON) clauses.

Retrieving id from a row that I've just written to the database

How can I retrieve an id from a row that I've just written to the database?
Basically, I have a function in my ASP.NET a booking form that needs to write to two tables, but I need the id from what's been written in table 1, to also be store in table 2.
So:
write to table 1
retrieve id from table 1
write to table 2
How can I achieve this?
Regards
Tea
In Asp.Net with a Sql 2008 server, you can use the ExecuteScalar function like this:
string query = "INSERT INTO Table1 (id_field)
OUTPUT SCOPE_IDENTITY()
VALUES (...)";
OR
string query = "INSERT INTO Table1 (...) VALUES (...); SELECT SCOPE_IDENTITY() ";
In the last example, notice I'm performing an INSERT and then a SELECT in the same request...
And to get the identity use:
int lastId = (int)command.ExecuteScalar();
If you're using SQL Server use SCOPE_IDENTITY()
http://msdn.microsoft.com/en-us/library/ms190315.aspx
INSERT INTO Table1 ...
DECLARE #RecordID int = SCOPE_IDENTITY()
INSERT INTO Table2 ... VALUES (#RecordID....)
Without using stored procedures, you could attach a SELECT statement to the end of your SQL:
cmd.CommandText = "INSERT INTO Table 1 ...... ; SELECT SCOPE_IDENTITY()"
int recordId = (int)cmd.ExecuteScalar();

Read last Inserted row in Sql according to its Time stamp

sql has a Table called emp.
emp(emp_id int IDENTITY primary key, EmployeeName varchar(50),.......)
I want to Insert a record to above table. Here is my code in asp.net.
DBconnection dbcon = new DBconnection();
string query = "insert into emp values('" + TextBox_EmpName.Text + "','" + ....);
int no1 = dbcon.insertQuery(query);
I have another table called emp-relation
emp-relation(emp_id int primary key, count int, ....)
-- foreign key (emp_id)references emp(emp_id)
My problem is when I inserting the emp row ,I dont know what is the emp_id since it created by auto. And when I am going to insert to emp-relation , I want to get emp-id since it is the foreign key.
How can I do this? Is there any way to read last Insert row in Sql according to Time stamp or some thing? I believe that records are not sorted according to inserted timestamp in nature. please help me.
There's bascally two ways. The first way is to return the new ID from the first insert query:
insert into emp values(...)
select scope_identity() as NewID
The second way is to lookup the first row when you insert into the relation table:
insert emp-relation
(emp_idm, ...)
select emp_id
, ...
from emp
where emp_name = #EmpName
You have to pass in enough columns to make the reference unique.

Linq to Entities: Left join to get items NOT found in the join

I've got two un-related (no FK's defined) tables. The first table contains some tasks for which a user may not have access. I need to find all those tasks - in this case, the joined table would contain nulls. How do I get them?
Here's the setup:
TimeData table
- userID
- taskID
- hours
ApprovedTasks table (the one that should contain nulls)
- taskID
- userID
The SQL query would look like this:
select * from TimeData td
left join ApprovedTasks at
on at.taskID = td.taskID and at.userID = td.userID
where at.taskID is null
Any way to pull that off using a LINQ to Entity query?
TIA
Check out... Disjoint Union in LINQ
This should work...
var approvedTaks = from at in ApprovedTasks.Except(
from at2 in ApprovedTasks
where at2.userID == userId and at2.taskID==taskId
select at2)
where at.userID == userId and at.taskID==taskId
select at;
but sorry don't have the database handy to test it.

Resources