hi m getting the following exception:
System.Data.SqlClient.SqlException: Incorrect syntax near '4'.
the following is what i was trying:

public void hostel_cpacity(ManageHostelRoomsBE hmr)
            string str;
            string conString =                           System.Configuration.ConfigurationManager.ConnectionStrings["Hosteluog"].ConnectionString;
            SqlConnection con = new SqlConnection(conString);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            DataTable dt = new DataTable();
            DataTable dt1 = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter();
            str = "select HostleName from tbl_Hostel where (HostelID ='" + hmr.HostelID + "')";
            cmd.CommandText = "insert into hostel_info(hostelName,rooms,capacity) values ('" + str + "','" + hmr.RoomNO + "','" + hmr.CapacityID + "')";



plz help me in this regard.

Recommended Answers

All 5 Replies

I'd do it like this:

"insert into hostel_info(hostelName,rooms,capacity) select HostleName, '" + hmr.RoomNO + "','" + hmr.CapacityID + "'  from tbl_Hostel where (HostelID ='" + hmr.HostelID + "')";

Clean example:

INSERT INTO hostel_info(hostelName,rooms,capacity) 
SELECT HostleName, 'rooms', 'capacity'  
FROM tbl_Hostel 
WHERE (HostelID = 'id')

but i think when we have to insert into the table we can work only with a single table. there is a problem while using a sub query for making insertion into table...

No, there is not a problem. There is only methods to do it. You can make a insert from a select, like I posted.

In AleMonteiro's example, he is only showing you how to insert into one table, but from the results of a query from another.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.