My database tables list in dropdownlist...when i select table from dropdown table display in GridView. I want to edit,delete & insert dynamically in GridView. Please give me solution....
Check out these links:
http://geekswithblogs.net/dotNETvinz/archive/2009/02/22/gridview-insert-edit-update-and-delete--the-ado.net-way.aspx
http://msdn.microsoft.com/en-us/library/aa479339.aspx
Say you have three database tables, Customer, Orders and Products - do you mean the names of these tables appear in your dropdownlist?
If so, when a table name is selected in the dropdownlist (and perhaps an 'Edit' button is clicked), you'll need to bind your GridView to the selected table's data.
You could do this with inline SQL - build it from the DDL:
string _selectString = "SELECT * FROM " + ddlTables.SelectedValue ; //Remember to include the schema in the dropdownlist's value property
And then use this SQL to fetch back the data and bind your grid to it.
A better way would be to wrap up the SQL in a stored procedure that uses SQL Server's INFORMATION_SCHEMA schema (which holds all the database's objects)
CREATE PROCEDURE MySchema.GetTableData
#TableName VARCHAR(Max),
#SchemaName VARCHAR(MAX) --Pass in the relevant Schema
AS
BEGIN
SET NOCOUNT ON
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #TableName
AND TABLE_SCHEMA = #SchemaName
END
and get the data out this way. The only difference to the way you're probably already doing this is to set the SQLCommand's CommandType property to CommandType.StoredProcedure and to pass in the tablename and schema name as SQLParameters.
More information about ASP.Net and Stored Procedures:
http://www.c-sharpcorner.com/UploadFile/gtomar/storedprocedure12052007003126AM/storedprocedure.aspx
Once you've got the data from the table you just use the code & process linked to by #Brian.
hth.
Related
I am facing this weird problem and spent several hours. Little help would be greatly appreciated.
This is an ASP.NET MVC app. For simplicity, I have two SQL tables, Employee (ID, Name, JoiningDate) and Benefits (ID, EmployeeID). Both IDs are identity colums. When a new employee joins the company, an entry is created in the Employee table as well as Benefits table.
The stored procedure looks like this
alter procedure usp_CreateEmployee
#Name nvarchar(100),
#JoiningDate datetime
as
declare #lastIdentity int
insert into Employee(Name, JoiningDate) values(#Name, #JoiningDate)
select #lastIdentity = ident_current('Employee')
insert into Benefits(EmployeeID) values(#lastIdentity)
C# side I am using Dapper
var parameters = new DynamicParameters();
parameters.Add("#Name", name);
parameters.Add("#JoiningDate", joiningDate);
affectedRows = connection.Execute("usp_CreateEmployee", parameters, null, commandType: CommandType.StoredProcedure);
When I execute the stored procedure in SSMS, everything works perfect. (ident_current returns the last inserted id). However, when the user interface creates employee (through razor page), a NULL gets inserted as EmployeeID in Benefits table. Employee table shows correct Employee ID.
Doesn't look like a SQL problem. Is there anything wrong with my code? Could this be Dapper related (though I dont think so)?
I think the problem was on the "ident_current". Please refer here: https://sqlperformance.com/2014/01/t-sql-queries/ident-current
alternatively, you may try below sql script.
alter procedure usp_CreateEmployee
#Name nvarchar(100),
#JoiningDate datetime
as
declare #lastIdentity int
insert into Employee(Name, JoiningDate) values(#Name, #JoiningDate)
select top(1) #lastIdentity=ID from Employee where Name=#Name
order by ID desc
insert into Benefits(EmployeeID) values(#lastIdentity)
I am trying to create tables dynamically in a SQL Server database.
Like this with input from a textbox:
ALTER PROCEDURE [dbo].[opretNyEsyn]
#Navn NVARCHAR(100)
AS
BEGIN
DECLARE #SQLString NVARCHAR(MAX)
SET #SQLString = 'create table ' + QUOTENAME(#Navn) +
'([EsynNummer][int]Identity(1,1),
[Dato][datetime])'
END
But nothing happens when I run the method from the form, the table isn't created, and I get no errors.
What am I missing?
Notice. This is just a test table. It isn't supposed to look like this in the end.
Thanks in advance
You are just creating the statement, but in order to create the tables, you need to Execute the statement using the EXEC statement of sp_executesql SP. Add an execute statement to your Procedure. Like this
ALTER PROCEDURE [dbo].[opretNyEsyn]
#Navn nvarchar(100)
as
Begin
declare #SQLString nvarchar(max)
set #SQLString = 'create table ' + QUOTENAME(#Navn)+
'([EsynNummer][int]Identity(1,1),
[Dato][datetime])'
exec(#SQLString)-- Execute the Statement
End
Go
You need to execute dynamic SQL:
ALTER PROCEDURE [dbo].[opretNyEsyn]
#Navn SYSNAME
as
Begin
declare #SQLString nvarchar(max);
set #SQLString = 'create table ' + QUOTENAME(#Navn)+
'([EsynNummer][int]Identity(1,1),
[Dato][datetime])';
EXECUTE (#SQLString);
End;
Anyway I recommend to read The Curse and Blessings of Dynamic SQL and Packaging Permissions in Stored Procedures:
CREATE TABLE #tbl
The desire here is to create a table of which the name is determined at run-time.
If we just look at the arguments against using dynamic SQL in stored procedures, few of them are really applicable here. If a stored procedure has a static CREATE TABLE in it, the user who runs the procedure must have permissions to create tables, so dynamic SQL will not change anything. Plan caching obviously has nothing to do with it. Etc.
Nevertheless: Why? Why would you want to do this? If you are creating tables on the fly in your application, you have missed some fundamentals about database design. In a relational database, the set of tables and columns are supposed to be constant. They may change with the installation of new versions, but not during run-time.
I'm using SQLite, which doesn't support adding a constraint to an existing table.
So I can't do something like this (just as an example):
ALTER TABLE [Customer]
ADD CONSTRAINT specify_either_phone_or_email
CHECK (([Phone] IS NOT NULL) OR ([Email] IS NOT NULL));
Are there any workarounds for this scenario?
I know:
I can add a constraint for a new table, but it isn't new (and it's generated by my ORM, EF Core)
I can do a "table rebuild" (rename table, create new one, copy old data, drop temp table) but that seems really complex
Ideas
Can I somehow make a copy of the table into a new table, with some schema changes?
Or "get" the schema somehow, and edit it in a SQL script, then add a table with that schema?
To make a copy of a table with some schema changes, you have to do the creation and the copying manually:
BEGIN;
CREATE TABLE Customer_new (
[...],
CHECK ([...])
);
INSERT INTO Customer_new SELECT * FROM Customer;
DROP TABLE Customer;
ALTER TABLE Customer_new RENAME TO Customer;
COMMIT;
To read the schema, execute .schema Customer in the sqlite3 command-line shell.
This gives you the CREATE TABLE statement, which you can edit and execute.
To change the table in place, you can use a backdoor.
First, read the actual table definition (this is the same as what you would get from .schema):
SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'Customer';
Add your CHECK constraint to that string, then enable write access to sqlite_master with PRAGMA writable_schema=1; and write your new table definition into it:
UPDATE sqlite_master SET sql='...' WHERE type='table' AND name='Customer';
Then reopen the database.
WARNING: This works only for changes that do not change the on-disk format of the table. If you do make any change that changes the record format (such as adding/removing fields, or modifying the rowid, or adding a constraint that needs an internal index), your database will blow up horribly.
I have a form that has the 'data entry' property set to yes. It is bound to a table. When I start filling in the form it automatically saves it. I do not want this to happen. I only want the form to save to the table when I press a button. Any easy way to do this? w/o vba. If i can only do this with vba let me know how to do it that what.
The best way to do this is with an unbound form. When the user clicks save, you can run a query to update your table from the controls.
Using a recordset
Dim rs As Recordset
Set rs=CurrentDB.Openrecordset("MyTable")
rs.AddNew
rs!Field1 = Me.Field1
rs.Update
If you wanted to update a record where you already knew the primary key, you could say:
Dim rs As Recordset
Set rs=CurrentDB.Openrecordset("SELECT * FROM MyTable WHERE ID=" & Me.txtID)
rs.Edit
rs!Field1 = Me.Field1
rs.Update
Using a query that you have created in the query design window
SQL for the query
INSERT INTO MyTable (Field1)
VALUES ( Forms!MyForm!Field1 )
VBA
This will give a warning
DoCmd.OpenQuery "MyQuery"
This will not
CurrentDb.Execute "Query2", dbFailOnError
You could also use dynamic SQL or a query with parameters that you assign in code.
I have an ASP.NET 3.5 web form with a DropDownList bound to a table of company names in a database. I also have a data bound GridView which I would like to update with data from the database depending on the company name selected in the DropDownList, so that the SelectCommand for the GridView's SqlDataSource is:
SELECT Registration, Telephone, Profile FROM {CompanyName}_VehicleData
Where {CompanyName} is whatever is selected in the DropDownList. I've used the Command and Parameter Editor to create a ControlParameter pointing to the SelectedValue of the DropDownList, but I don't know how to write the SelectCommand query to concatenate the parameter to '_VehicleData'. Any thoughts.
If you are using a sqldatasource you could set the select command in the code behind.
<sqldatasource>.SelectCommand = "select registration, telephone, profile " & _
"from " & <dropdown>.selectedvalue & "_VehicleData"
<sqldatasource>.SelectType = SqlDataSourceCommandType.Text
#Colin: You said that the solution is writing a stored procedure that evaluates whether the concatenated value (DropDown.SelectedValue + "_VehicleData") maps to a real table using the INFORMATION_SCHEMA.TABLES view before injecting it into a SQL command. Can you please give a code snippet for the stored proc?