SQL server command to create server alias? - sql

MSDN states that there are 4 steps in creating a server alias:
In SQL Server Configuration Manager, expand SQL Server Native Client Configuration, right-click Aliases, and then click New Alias.
In the Alias Name box, type the name of the alias. Client applications use this name when they connect.
In the Server box, type the name or IP address of a server. For a named instance append the instance name.
In the Protocol box, select the protocol used for this alias. Selecting a protocol, changes the title of the optional properties box
to Port No, Pipe Name, or Connection String.
But instead of doing it the "UI way", is there a SQL command to do it?

The configuration of server aliases for clients is a client configuration rather than a SQL server configuration. As such there's no SQL command to create one, much the same as there is no SQL command to create an ODBC connection.
You can script the configuration using WMI through powershell, the place to start is:
http://msdn.microsoft.com/en-us/library/ms179354.aspx
and http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.wmi.aspx
Here is a powershell example using wmi to create an alias
# List existing aliases
Get-WmiObject -Namespace 'root\Microsoft\SqlServer\ComputerManagement10' -Class 'SqlServerAlias' |
Format-Table -Property 'AliasName', 'ServerName', 'ProtocolName', 'ConnectionString'
# Example script to create an alias
$alias = ([wmiclass] '\\.\root\Microsoft\SqlServer\ComputerManagement10:SqlServerAlias').CreateInstance()
$alias.AliasName = 'bob'
$alias.ConnectionString = '1433' #connection specific parameters depending on the protocol
$alias.ProtocolName = 'tcp'
$alias.ServerName = 'example_server'
$alias.Put() | Out-Null;

To edit an existing alias, I would do a delete\insert.
I use this PS to delete the alias entries (SQL 2016):
$alias=Get-WmiObject -namespace 'root\Microsoft\SqlServer\ComputerManagement13' -class 'SqlServerAlias' -filter "AliasName='YourAliasName'"
$alias.Delete()

Related

Connecting to SQL Server using Perl using DBI?

I am trying to connect to SQL server using Perl DBI module, I have tried all the connection string format still Perl is throwing invalid connection string error.
I have already tried code snippet available on perl monk website.
#!/usr/bin/perl -w
use strict;
use DBI;
# Set up variables for the connection
my $server_name = '00.120.124.1;3181';
my $database_name = 'abcd';
my $database_user = 'kkkk';
my $database_pass = 'password';
my $DSN = 'driver={SQL Server};server=$server_name;da
+tabase=$database_name;uid=$database_user;pwd=$database_pass;';
my $dbh = DBI->connect("DBI:ODBC:$DSN") || die "Couldn't open database
+: $DBI::errstr\n";
Expected result is to connect to Database.
failed: [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). (SQL-01000) [state was 01000 now 01S00] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (SQL-01S00) at perl.pl line 16. Couldn't open database +: [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied. (SQL-08001) [state was 08001 now 01000] Invalid connection string attribute (SQL-01S00)
The lines of your post that begin with +
+tabase=$database_name;uid=$database_user;pwd=$database_pass;';
+: $DBI::errstr\n";
were incorrectly copied and pasted from perlmonks.org. The leading + sign is a convention that indicates a long line was split. You should delete the + and join the line to the previous line, so that your code will read
my $DSN = 'driver={SQL Server};server=$server_name;database=$database_name;uid=$database_user;pwd=$database_pass;';
my $dbh = DBI->connect("DBI:ODBC:$DSN") || die "Couldn't open database: $DBI::errstr\n";
Your error message contains the following:
SQL Server does not exist or access denied
Your set-up code contains the following:
my $server_name = '00.120.124.1;3181';
'00.120.124.1;3181' is not a valid server name or IP address. You should correct the IP address section (it can't start with '00') and remove the port into a separate parameter.
You also have the username and password as part of your DSN. I don't know if DBD::ODBC supports that usage (it's not mentioned in the documentation) but it's more traditional to have those as separate parameters to the connect() call.
All in all, I think you want something more like this:
my $server_name = '00.120.124.1'; # But this needs to be corrected
my $server_port = 3181;
my $database_name = 'abcd';
my $database_user = 'kkkk';
my $database_pass = 'password';
my $DSN = "driver={SQL Server};server=$server_name;port=$server_port;database=$database_name";
my $dbh = DBI->connect("DBI:ODBC:$DSN", $database_user, $database_pass)
|| die "Couldn't open database: $DBI::errstr\n";
Also note that I've changed the quote characters used to create your $DSN variable from single quotes to double quotes. Variables are not expanded in signel quotes, so you weren't getting the values of $server_name, etc. in your DSN.
The better way to connect is with the DBD::Sybase module. The name wouldn't suggest it but SQL Server takes its lineage from Sybase. That way you can avoid ODBC. http://metacpan.org/pod/DBD::Sybase#Using-DBD::Sybase-with-MS-SQL

How do I get a user input and apply it in a sql statement in bash?

I have two scripts. One is named sqlscript.sql and the other is named script.sh I have all of the queries needed written in my sql script. They are just a bunch of update statements. For example:
UPDATE xxDev.SYS_PARAMS SET val = 'serverName' WHERE lower(name) = 'enginebaseurl';
I'm running the .sql script IN the .sh script. When the .sh script runs, I want it to prompt the user for a server name and take that user input and replace it in serverName in the sql statements.
I'm brand new to both bash scripting and this website, so I hope I'm making sense asking this question. I'm using PuTTY if that makes a difference at all.
Suppose you use MySQL, try something like:
# TODO: prompt user for server name and store it into variable serverName
serverName="get from user"
cat <<"EOF" | mysql -u user1 -p passwd -h server1 -P 3306 -D db1
UPDATE xxDev.SYS_PARAMS SET val = '$serverName' WHERE lower(name) = 'enginebaseurl';
EOF
So in this example, you embed the sql script into the .sh so that you don't have to maintain two files.
I would probably use a variable
set #val 'serverName'
UPDATE xxDev.SYS_PARAMS SET val = #val WHERE lower(name) = 'enginebaseurl';
You can split the sqlscript.sql into
set-val.sql
set #val 'serverName'
and the actual update statements. Then you can recreate the set-val.sql from your user input:
echo -n "enter server: "
read server
echo "set #val '$server' > set-val.sql
and then you forward both files to mysql:
cat set-val.sql sqlscript.sql | mysql
You should probably use this only for internal things, it seems a little fragile.
I'm going let you figure out how to pass a shell parameter into your sql command, but here's an incredibly cool way to query the user for the server name. It might even be POSIX compliant.
#!/bin/sh
echo -n "Hit me with that server name: "; read serverName
echo "${serverName}! Outstanding! Pick up \$200 when you pass Go!"

Changing default database in RODBC for sql server database

I have tried to connect a Sql server database to R using:
conn<-odbcConnect("dsnDb",uid="",pwd="")
It retrieves the default database 'master' instead of the database I need. How can I manually get a particular database?
So, there's no way to do this within the RODBC package, but here's a function which achieves the same thing:
Assuming your DSN is called "MyODBClink":
MakeChannel = function(dbName){
system(paste("REG ADD HKEY_CURRENT_USER\\Software\\ODBC\\ODBC.INI\\MyODBClink /f /v \"Database\" /t REG_SZ /d ", "\"", dbName ,"\"", sep=""),intern=T)
return(odbcConnect("MyODBClink"))
}
The way this function works is to edit the details of the registry (I'm assuming you're on Windows) for that particular DSN to point to the correct database, and then return an open connection to that DSN.

Powershell 4.0 - plink and table-like data

I am running PS 4.0 and the following command in interaction with a Veritas Netbackup master server on a Unix host via plink:
PS C:\batch> $testtest = c:\batch\plink blah#blersniggity -pw "blurble" "/usr/openv/netbackup/bin/admincmd/nbpemreq -due -date 01/17/2014" | Format-Table -property Status
As you can see, I attempted a "Format-Table" call at the end of this.
The resulting value of the variable ($testtest) is a string that is laid out exactly like the table in the Unix console, with Status, Job Code, Servername, Policy... all that listed in order. But, it populates the variable in Powershell as just that: a vanilla string.
I want to use this in conjunction with a stored procedure on a SQL box, which would be TONS easier if I could format it into a table. How do I use Powershell to tabulate it exactly how it is extracted from the Unix prompt via Plink?
You'll need to parse it and create PS Objects to be able to use the format-* cmdlets. I do enough of it that I wrote this to help:
http://gallery.technet.microsoft.com/scriptcenter/New-PSObjectFromMatches-87d8ce87
You'll need to be able to isolate the data and write a regex to capture the bits you want.

Calling sproc on SQL Azure from Invoke-Sqlcmd

The form to hit a regular sql server:
$server = "192.168.1.1"
$myDatabase = "Adventures"
$myUser = "Joe"
$myPass = "BadPass"
Invoke-Sqlcmd -ServerInstance $server -Database $myDatabase -Username $myUser -Password $myPass
For Azure SQL http://www.connectionstrings.com/sql-azure/ tells me to bracket the servername as:
[plkahglkhjl].database.windows.net
but that gets me a error message that the server can not be found or was not accessible. It's behaving as if it were a firewall blocking but I have a open connection in SSMS without problem.
Is there another set of validation/authentication that PowerShell scripts have to deal with?
thx
ConnectionStrings.com is just indicating that you need to replace those fields with your own, not that you actually need brackets.
1) You do not need to bracket your server name
plkahglkhjl.database.windows.net
2) You do need to put the server name in the UserName
Joe#plkahglkhjl
More details here: Error connecting to SQL Azure Database