Laravel8 : get column name from table SQL Server - sql-server

I've tried this code:
//controller
$model = new Mymodel;
$table = $model->getTable();
$columns = Schema::getColumnListing($table);
//view.blade.php
{{print_r($columns)}}
but the result only give this output: Array ( [0] => * ) 1
More Information:
I need to connect to SQL Server database with Forticlient VPN. I think it shouldn't be the problem. But, tell if there's something I've missed.

After struggling looking for any answer, and looking for answer generally about how to get the column name straight from SSMS, I've made my temporary own solution. Here's the code:
$model = new Mymodel;
$table = $model->getTable();
$schema = DB::table('INFORMATION_SCHEMA.COLUMNS')
->select('COLUMN_NAME')
->where("TABLE_NAME", $table)
->get();
My own answer is only improvement from the base query to get column name straight from the SSMS, here the query:
select COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'mytable_name'

Related

Perl - Get the structure of a sqlite database using DBI

I need to test the structure of my SQLite database which is composed by a unique table with let's say 2 columns (id, name). I can't figure out the SQL query to get the table schema of my database.
I am able to get all the content of the database using the DBI method selectall_arrayref(). However it only returns an array containing the values inside my database. This information is useful but I would like to have a SQL query which returns something like id, name (Basically, the table schema).
I tried the following queries : SHOW COLUMNS FROM $tablename but also SELECT * from $tablename (This one returns all the table content).
Here is my implementation so far :
# database path
my $db_path = "/my/path/to/.database.sqlite";
my $tablename = "table_name";
sub connect_to_database {
# Connect to the database
my $dbh = DBI->connect ("dbi:SQLite:dbname=$db_path", "", "",
{ RaiseError => 1, AutoCommit => 0 },
)
or confess $DBI::errstr;
return $dbh;
}
sub get_database_structure {
# Connect to the database
my $dbh = &connect_to_database();
# Get the structure of the database
my $sth = $dbh->prepare("SHOW COLUMNS FROM $tablename");
$sth->execute();
while (my $inphash = $sth->fetrow_hashref()) {
print $inphash."\n";
}
# Disconnect from the database
$dbh->disconnect();
}
# Call the sub to print the database structure
&get_database_structure();
I expect the output to be the structure of my table so id, name but I raise an error : DBD::SQLite::db prepare failed: near "SHOW": syntax error
I can't find the good query. Any comments or help would be greatly appreciated.
Thanks !
What you're looking for is really just the SQL lite query for the table and column information. This answer SQLite Schema Information Metadata has the full details if this query doesn't work for you, but under the assumption you're using whatever the 'recent' version mentioned in one of the answers is, you can do something like this:
# Get the structure of the database
my $sth = $dbh->prepare("<<END_SQL");
SELECT
m.name as table_name,
p.name as column_name
FROM sqlite_master AS m
JOIN pragma_table_info(m.name) AS p
ORDER BY m.name, p.cid
END_SQL
$sth->execute();
my $last = '';
while (my $row = $sth->fetchrow_arrayref()) {
my ($table, $column) = #$row;
if ($table ne $last) {
print "=== $table ===\n";
$last = $table;
}
print "$column\n";
}
After digging through the community answers I finally find a solution using the pragma table_info.
sub get_database_structure {
# Connect to the database
my $dbh = &connect_to_database ();
# Return the structure of the table execution_host
my $sth = $dbh->prepare('pragma table_info(execution_host)');
$sth->execute();
my #struct;
while (my $row = $sth->fetchrow_arrayref()) {
push #struct, #$row[1];
}
# Disconnect from the database
$dbh->disconnect ();
return #struct;
}
It returns a list of the columns name present in the table execution_host.
Thanks for the help !

sqlsrv does not support named parameters to queries

I'm using PHP7 (with Droctrine 2.5.13) on Ubuntu 16.04 x64.
I'm trying to do a prepared statment to a Microsoft SQL database using a named variable like so:
$sql = 'SELECT DISTINCT
"PRODUCT"."NUMBER"
FROM
"PRODDB"."PRODUCT"
WHERE
"PRODUCT"."NUMBER" LIKE :productNumber
ORDER BY
"PRODUCT"."NUMBER" DESC';
$query = $this->db->prepare($sql);
$query ->bindParam(':productNumber' , $ofSearch);
$status = $query->execute();
$result = $query->fetchAll();
But SQL tell me that I need to use question mask instead of the named parameter
Error : sqlsrv does not support named parameters to queries, use question mark (?)
If I replace the named variable by a question mark it work fine.
The example below work fine:
$sql = 'SELECT DISTINCT
"PRODUCT"."NUMBER"
FROM
"PRODDB"."PRODUCT"
WHERE
"PRODUCT"."NUMBER" LIKE ?
ORDER BY
"PRODUCT"."NUMBER" DESC';
$query = $this->db->prepare($sql);
$query ->bindParam(1 , $ofSearch);
$status = $query->execute();
$result = $query->fetchAll();
Using question mark is a terrible way to do prepared statement as when you have very complex query with over 20 parameters it become a nightmare to maintain.
Do you have any idea if there is a solution to this problem or at least a workaround?

Cake 2.X retrive data from rawQuery

As show at CakePHP 2.1.x - Run a query without any models in AppController
I have a query,
$q = "select id from table where id=123";
$db = ConnectionManager::getDataSource('default');
$qr = $db->rawQuery($q);
ok (!), it works... But, how to get my data?? Where the tutorial examples?
I need something like $data = $qr->fetchAll() method or $id = getMyData($qr) function.
I believe this may be the solution or at least a point in the right direction.
$q = "select id from table where id=123";
$db = ConnectionManager::getDataSource('default');
$myData = $db->query($q);

How do you use delete, update, insert in joomla mvc from the file you create

I have been able to create simple MVC app to display the form and use information from the database. [ so sql I use SELECT ].
However, when I use 'update' or 'delete' the data in the database stay the same. I don't understand!?!
[ I use controller.php call model and pass id to match with the row in the table]
I check data that pass in there, and it did echo the value of id.
The page I load from the controller that call method in model has complete without the error (it could be that the syntax is right, but logic is wrong).
so i start to change sql statement to SELECT and it gives me the value that match with $id param'
I don't understand? any clue?
$query = JFactory::getDbo()->getQuery(true);
$db =& JFactory::getDBO();
$query = "DELETE FROM `menutables` WHERE `id2` = $id ";
$db->setQuery($query);
$db->query(); // this line I also take it out to test, it is fine but no data change either
Do you try to modify a Joomla database or a personal one?
Look at this pages :
http://docs.joomla.org/How_to_connect_to_an_external_database
http://docs.joomla.org/How_to_use_the_database_classes_in_your_script#Tips.2C_Tricks_.26_FAQ
try to use either
$query = "DELETE FROM #__menutables WHERE id2 = '$id' ";
or
$query = "DELETE FROM #__menutables WHERE id2 = '".$id."' ";
it'll work fine then.
Deleting a Record
delete query in Joomla 2.5.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
// delete all custom keys for user 1001.
$conditions = array(
$db->quoteName('user_id') . '=1001',
$db->quoteName('profile_key') . '=\'custom.%\''
);
$query->delete($db->quoteName('#__user_profiles'));
$query->where($conditions);
$db->setQuery($query);

T-SQL query to show table definition?

What is a query that will show me the full definition, including indexes and keys for a SQL Server table? I want a pure query - and know that SQL Studio can give this to me, but I am often on "wild" computers that have only the most bare-bones apps and I have no rights to install studio. But SQLCMD is always an option.
UPDATE: I have tried sp_help, but is just yields one record which shows Name, Owner, Type and Created_Datetime. Is there something else I am missing with sp_help?
Here is what I call:
sp_help airports
Note that I really do want the DDL that defines the table.
There is no easy way to return the DDL. However you can get most of the details from Information Schema Views and System Views.
SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customers'
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
WHERE TABLE_NAME = 'Customers'
SELECT name, type_desc, is_unique, is_primary_key
FROM sys.indexes
WHERE [object_id] = OBJECT_ID('dbo.Customers')
Have you tried sp_help?
sp_help 'TableName'
Visit http://www.stormrage.com/SQLStuff/sp_GetDDL_Latest.txt.
You will find the code of sp_getddl procedure for SQL Server.
The purpose of the procedure is script any table, temp table or object.
USAGE:
exec sp_GetDDL GMACT
or
exec sp_GetDDL 'bob.example'
or
exec sp_GetDDL '[schemaname].[tablename]'
or
exec sp_GetDDL #temp
I tested it on SQL Server 2012, and it does an excellent job.
I'm not the author of the procedure. Any improvement you make to it send to Lowell Izaguirre (scripts#stormrage.com).
The easiest and quickest way I can think of would be to use sp_help
sp_help 'TableName'
Use this little Windows command-line app that gets the CREATE TABLE script (with constraints) for any table. I've written it in C#. Just compile it and carry it on a memory stick. Perhaps someone can port it to Powershell.
using System;
using System.Linq;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace ViewSource
{
public class ViewSource
{
public static void Main(string[] args)
{
if (args.Length != 6)
{
Console.Error.WriteLine("Syntax: ViewSource.exe <server>" +
" <user> <password> <database> <schema> <table>");
}
Script(args[0], args[1], args[2], args[3], args[4], args[5]);
}
private static void Script(string server, string user,
string password, string database, string schema, string table)
{
new Server(new ServerConnection(server, user, password))
.Databases[database]
.Tables[table, schema]
.Script(new ScriptingOptions { SchemaQualify = true,
DriAll = true })
.Cast<string>()
.Select(s => s + "\n" + "GO")
.ToList()
.ForEach(Console.WriteLine);
}
}
}
Since SQL 2012 you can run the following statement:
Exec sp_describe_first_result_set #tsql= N'Select * from <yourtable>'
If you enter a complex select statement (joins, subselects, etc), it will give you the definition of the result set. This is very handy, if you need to create a new table (or temp table) and you don't want to check every single field definition manually.
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-describe-first-result-set-transact-sql
sp_help 'YourTableName'
This will return columns, datatypes, and indexes defined on the table:
--List all tables in DB
select * from sysobjects where xtype = 'U'
--Table Definition
sp_help TableName
This will return triggers defined on the table:
--Triggers in SQL Table
select * from sys.triggers where parent_id = object_id(N'SQLTableName')
I know it's an old question, but exactly what I was looking for. Because I want to batch script some tables, I rewrote the C# code from Anthony Faull for PowerShell.
This one is uses Integrated Security:
Import-Module sqlps
$serverInstance = "<server>"
$database = "<database>"
$table = "<table>"
$schema = "<schema>"
$options = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$options.DriAll = $true
$options.SchemaQualify = $true
$connection = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection `
-ArgumentList $serverInstance
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server `
-ArgumentList $connection
$server.Databases.Item($database).Tables.Item($table, $schema).Script($options) `
| ForEach-Object -Process { $_ + "`nGO"}
And here with username and password:
Import-Module sqlps
$serverInstance = "<server>"
$user = "<user>"
$password = "<pasword>"
$database = "<database>"
$table = "<table>"
$schema = "<schema>"
$options = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$options.DriAll = $true
$options.SchemaQualify = $true
$connection = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection `
-ArgumentList $serverInstance
$connection.LoginSecure = $false
$connection.Login = $user
$connection.Password = $password
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server `
-ArgumentList $connection
$server.Databases.Item($database).Tables.Item($table, $schema).Script($options) `
| ForEach-Object -Process { $_ + "`nGO"}
Simply type the table name and select it and press ATL + F1
Say your table name is Customer then open a new query window, type and select the table name and press ALT + F1
It will show the complete definition of table.
A variation of #Anthony Faull's answer for those using LINQPad:
new Server(new ServerConnection(this.Connection.DataSource))
.Databases[this.Connection.Database]
.Tables["<table>", "dbo"]
?.Script(new ScriptingOptions {
SchemaQualify = true,
DriAll = true,
})
You'll need to reference 2 assemblies:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Smo.dll
And add namespace references as mentioned in Anthony's snippet.
SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'EMPLOYEES'
Try the sp_help stored procedure.
sp_help <>
Another way is to execute sp_columns procedure.
EXEC sys.sp_columns #TABLE_NAME = 'YourTableName'
As an addition to Barry's answer. The sp_help can also be used by itself to iterate all of the objects in a particular database. You also have sp_helptext for your arsenal, which scripts out programmatic elements, like stored procedures.
General table definition is shown using stored procedure sp_help, as said before:
sp_help 'table_name_in_current_db_context'
When using tables of multiple contexts is useful to prefix the command above with the desired context, instead of changing them with use db_xyz:
DB_Products..sp_help 'MyTable' -- for definition of MyTable in DB_Products
And it works with temp tables also:
tempdb..sp_help '#TempTable' -- for definition of #TempTable in current context.
There is an easy way to get DDL scripts for any database object.
Open SQL Server Management Studio
Connect to the source database server.
Expand the databases tree.
Right-click on the database with the tables to export.
In the sub-menu, expand "Tasks".
In the sub-menu, choose "Generate Scripts..."
Use the wizard to choose the objects to export.
For the scripting options, choose 1 script per object.
This will export a file for every table, view, stored proc, user, role, or schema you chose. Take that to the destination computer.

Resources