Querying Active Directory with T-SQL - sql

Have tried:
EXEC master.dbo.sp_addlinkedserver
#server = N'ADSI',
#srvproduct=N'Active Directory Services',
#provider=N'ADsDSOObject',
#datasrc=N'server_name.your_domain.com'
EXEC master.dbo.sp_addlinkedsrvlogin
#rmtsrvname=N'ADSI',
#useself=N'False',
#locallogin=NULL,
#rmtuser=N'your_domain\domain_user',
#rmtpassword='********'
SELECT *
FROM OPENQUERY (ADSI, 'SELECT *
FROM ''LDAP://DC=your_domain,DC=com''')
Getting this error:
Msg 7321, Level 16, State 2, Line 1
An error occurred while preparing the query "SELECT * FROM 'LDAP://DC=your_domain,DC=com'" for execution against OLE DB provider "ADsDSOObject" for linked server "ADSI".
I have already confirmed mine and the SQL Server Service domain accounts have read access to AD, and that the "Allow inprocess" is enabled on the ADsDSOObject provider is selected.
Any thoughts would be appreciated.

Every example I could find had: LDAP://DC=your_domain,DC=com as syntax. Well for our server (and maybe other's) it is: LDAP://DC=your_domain,DC=internal
As suggested by someone, I used the Softerra LDAP browser (free) and opened the server, clicked on the top node and found distinguished name entry listed as: DC=your_domain,DC=internal
Once I made that change, I could see the AD data.

Related

Execute stored procedure, but access denied

I tried to execute a stored procedure. But I this error below, at every stance of execution:
Msg 18456, Level 14, State 1, Line 3 Login failed for user 'NT
AUTHORITY\ANONYMOUS LOGON'.
Thank you.
This is what I try to execute:
USE [Artikelen]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[BerekenSKU]
#loc = N'AM',
#lev = N'3436',
#reset = true
SELECT 'Return Value' = #return_value
GO
I am using Microsoft SQL 2014
Error shows that there is credential issue. Please check this link.
This message indicates that you are attempting to access the linked
server by using Windows NT authentication to impersonate the client
connecting. Refer Link
Look at the stored procedure in question. The login is failing at the
linked server because whoever is calling it doesn't have mapped
credentials set up.
Refer this links:
sqlcmd: Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'
http://www.sqlservercentral.com/Forums/Topic548200-146-1.aspx
http://www.sqlservercentral.com/Forums/Topic1523177-1550-1.aspx
http://www.sqlservercentral.com/Forums/Topic246883-110-1.aspx
http://www.sqlservercentral.com/Forums/Topic246883-110-1.aspx

SQL bcp The semaphore timeout period has expired

I'm making a bulk copy onto a file of a select in my database.
DECLARE #cmd varchar(1000)
DECLARE #sql varchar(8000)
SET #cmd='"select * from [MyDB].[dbo].MyTable"'
SELECT #sql = 'bcp '+#cmd+' queryout C:\myfile.txt -c -t -T -S MyServer -U user -P password';
exec xp_cmdshell #sql;
If I change the parameters and I execute the same command on the database test on my machine it works, but on the database server I get this error:
Msg 121, Level 20, State 0, Line 0
A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The semaphore timeout period has expired.)
I check server name, user, password, table name and they are correct, so I cannot understand what I'm doing wrong.
Can someone help me with this issue?
thanks
Increase timeout seconds in connection string.
private static void OpenSqlConnection() {
string connectionString = GetConnectionString();
using(SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionTimeout: {0}",
connection.ConnectionTimeout);
}
}
static private string GetConnectionString() {
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file, using the
// System.Configuration.ConfigurationSettings.AppSettings property
return "Data Source=(local);Initial Catalog=AdventureWorks;" + "Integrated Security=SSPI;Connection Timeout=30";
}
I had the same error. A third-party tool was connecting to the database to extract data for import into a business intelligence system. Each extract/import would run for about 1 hour and there would be something like 10 to 15 separate queries in the process. Fortunately we had logging in place - so we knew at what time each of those queries was starting and ending. The extract/import process was saying that it was completing successfully after 30 minutes - rather than taking about 1 hour. I was able to isolate the query during which the process was failing. When I ran that query in SSMS I got the same error you've given in the question.
However, when I ran that query in another environment, I got an error that a subquery cannot return more than one row.
Sure enough, when I commented out my subqueries in the prod environment, the query ran without any error.
So ultimately, the root cause for me was a subquery returning more than one row - and the issue only appeared because for some reason, "bad data" got into the database - ie. that particular subquery should never have found a scenario where there is more than one row, and hence too, the error just began to appear one day. (For other people who are experiencing this error intermittently - it could be because it is only some of your queries - or one of your queries - that is failing).

Devise return incorect user ID?

I get the error shown below on sign in (via Devise)
Oddly, Rails/Devise seems to be returning a user id of '1' even though there is no user in my users table with an id of '1'. This seems to happen kind of randomly, I can't figure out what the problem is.
Here's the latest error message.
ODBC::Error: S1000 (9001) [Microsoft][SQL Server Native Client 11.0][SQL Server]The log for database '[redacted]' is not available. Check the event log for related error messages. Resolve any errors and restart the database.: EXEC sp_executesql N'UPDATE [users] SET [last_sign_in_at] = ''2012-11-12T16:58:34.020'', [current_sign_in_at] = ''2012-11-13T08:44:33.586'', [sign_in_count] = 69, [updated_at] = ''2012-11-13T08:44:33.630'' WHERE [users].[id] = 1; SELECT ##ROWCOUNT AS AffectedRows'
Here's the request params:
{"utf8"=>"✓",
"authenticity_token"=>"[redacted]=",
"user"=>{"email"=>"jkramxx#xx.com",
"password"=>"[FILTERED]",
"remember_me"=>"0"},
"commit"=>"Sign in"}
There actually is no user in the db with an id of "1", and theres nothing wrong with the server. The user jkramxx#xx.com has id of 60. ( user id 1 was deleted from the db a while ago). I thought it might be something in the session cookie so i deleted that as well).
I've seen similar odd behavior in the console, where I have been able to log in, but when I examine current_user in the debugger it shows the user having an id of '1' even though when I examine the db directly (using SQL Server Mgmt Studio) the user has id of 34 and there is no user with id of 1. Sometimes this beahvior goes away when I restart the debugger. All very random.
Any suggestions?
(Ruby 1.9.3./Rails 3.2.8 SQL Server 10 using ruby-obdc gem)

SQL Server OLEDB error with no details

I have a SQL Server Agent job running, which uses a stored procedure to do several operations, then exports some data to an xls spreadsheet and emails that spreadsheet. Most of the time it works, but several times a month the job fails with the error:
OLE DB provider 'Microsoft.Jet.OLEDB.4.0' reported an error. The provider did not give any information about the error. [SQLSTATE 42000] (Error 7399). The step failed.
Thanks, Microsoft, for the detailed error message. Anyway, the short term fix is usually to simply re-run the job. Usually this works, but in rarer cases it does not, and I must restart the SQL Server instance.
Here is how my code interacts with OLEDB:
Insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 5.0;Database=\\Excel\POStatus\POStatus.xls;',
'SELECT * FROM [POStatus$]')
Select --Tons of columns with tons of math and functions
FROM --5 tables joined together (left joins)
WHERE -- Tons of where conditions
Order by --Case statement for custom sorting
Set #vCommand = 'copy \\Excel\POStatus\POStatus.xls \\Excel\POStatus\POStatus_' + #vDate + '.xls'
EXEC master..xp_cmdshell #vCommand , NO_OUTPUT
... omitted for brevity...
Set #nvSubject = ' POStatus ' + #vDate
Set #nvMessage = ' This is an automated message, please respond to the IS department, thank you '
Set #nvMessage = #nvMessage + char(13) + char(10)
Set #nvAttachments = '\\Excel\POStatus\POStatus_' + #vDate + '.xls'
Exec master..xp_sendmail
#recipients = #nvRecipients , #copy_recipients = #nvCopy_recipients ,
#subject = #nvSubject , #message = #nvMessage ,
#query = #nvQuery , #width = #iWidth , #attachments = #nvAttachments
So, what is the cause of this, and how can I prevent it?
When you call OPENROWSET, it load the DLL for OLEDB provider for Excel. These operations happens inside the SQL Server Stack memory. When a lot of call to older DLL (ActiveX/COM) are made, it's not impossible that your stack might get full. You can resolve this in 2 ways:
1) You make these operations outside a TSQL code. You can use a SSIS package for example but you have to change your code not to use OPENROWSET. You can use the DTS Wizard to do most of the job. This is my personnal recommandation !
2) You can also set SQL Server to have a bigger memory Stack by using the -g command parameter. I think 256 MB is the default and you can set it to 512. To do that you need to open the SQL Server Configuration Manager. Depending on your version, you should have a place to change the "Startup Parameters"

Linked Server Error using MSDTC

I am Showing An example of Stored Procedure For Data Transaction using "Linked Server" Between Two System Through Internet
Alter Proc [dbo].[usp_Select_TransferingDatasFromServerCheckingforExample]
#RserverName varchar(100), ----- Server Name
#RUserid Varchar(100), ----- server user id
#RPass Varchar(100), ----- Server Password
#DbName varchar(100) ----- Server database
As
Set nocount on
Set Xact_abort on
Declare #user varchar(100)
Declare #userID varchar(100)
Declare #Db Varchar(100)
Declare #Lserver varchar(100)
Select #Lserver = ##servername
Select #userID = suser_name()
select #User=user
Exec('if exists(Select 1 From [Master].[' + #user + '].[sysservers] where srvname = ''' + #RserverName + ''') begin Exec sp_droplinkedsrvlogin ''' + #RserverName + ''',''' + #userID + ''' exec sp_dropserver ''' + #RserverName + ''' end ')
set #RserverName='['+#RserverName+']'
declare #ColumnList varchar(max)
set #ColumnList = null
select #ColumnList = case when #ColumnList is not null then #ColumnList + ',' + quotename(name) else quotename(name) end from syscolumns where id = object_id('bditm') order by colid
set identity_insert Bditm on
exec ('Insert Into Bditm ('+ #ColumnList +') Select * From '+ #RserverName + '.'+ #DbName + '.'+ #user + '.Bditm')
set identity_insert Bditm off
set #RserverName=replace(replace(#RserverName,'[',''),']','')
Exec sp_droplinkedsrvlogin #RserverName,#userID
Exec sp_dropserver #RserverName
When i Running the Stored Procedure I Getting the different errors in different Time of Execution
Some time Shows this Error
"The operation could not be performed because OLE DB provider "SQLNCLI" for linked server "ServerName" was unable to begin a distributed transaction."
Another time Shows This Type of Error
OLE DB provider "SQLNCLI" for linked server "70.38.11.49" returned message "Protocol error in TDS stream".
OLE DB provider "SQLNCLI" for linked server "70.38.11.49" returned message "Communication link failure".
Msg 65535, Level 16, State 1, Line 0
Session Provider: Physical connection is not usable [xFFFFFFFF].
OLE DB provider "SQLNCLI" for linked server "70.38.11.49" returned message "Communication link failure".
Msg 65535, Level 16, State 1, Line 0
Session Provider: Physical connection is not usable [xFFFFFFFF].
OLE DB provider "SQLNCLI" for linked server "70.38.11.49" returned message "Communication link failure".
Msg 10054, Level 16, State 1, Line 0
TCP Provider: An existing connection was forcibly closed by the remote host.
I am Using the Windows Xp And SQL Server 2005 in Client side And Windows server 2003 and Sql server 2005 In Net Server
I Set the MSDTC in Both System
How Can i Solve This Problem (And also give the Correct Information For Setting The MSDTC in Windows XP And Windows server 2003)
I agree with the above posting that it might be a protocol issue but it might need to use Named Pipes as the interface.
Or it could be that the user account that the DTC service is runnning under only has local rights and no rights on the network. Use a domain account with sufficient rights on both machines to run DTC under.
Or it could be that you need to start a distributed transaction with BEGIN DISTRIBUTED TRANSACTION at the front-end of your process.
you might want to look at:
http://support.microsoft.com/kb/306212
and
http://support.microsoft.com/kb/937517
I can confirm it's a network connectivity issue. I have seen this before.
MSDTC agents must be able to connect to all database instances they are coordinating.
There was some MS-certified proceure for testing this... google for msdtc ping.
You also have to check the DNS name resolution in the IP network configuration.
For example, you have a server called server-a.mydomain.com and another one called server-b.otherdomain.com, log in the server-a and do a ping server-b (without the domain).
If it responds "Ping request could not find host server-b. Please check the name and try again." that is the problem.
Go to the Control Pannel > Network Connections > Right click in the network card > properties > Internet Protocol > Properties > Advanced > DNS > Append this DNS suffix in order. And here add the local domain: mydomain.com and then add the remote domain: otherdomain.com . Click OK until you exit
Now if you do the ping server-b it should repond something like:
Pinging server-b.otherdomain.com [192.168.1.2] with 32 bytes of data:
Reply from 192.168.1.2: bytes=32 time=12ms TTL=64
Reply from 192.168.1.2: bytes=32 time=9ms TTL=64
Now try to again to execute the distributed transaction.
A long shot, but i've encountered a similiar problem a while back, on MSSQL Server 7. It turned out that both system were required to contact each other by NetBios names, and since they were not part of a Domain (but were communicating over the WAN like in your case).
A simple solution, at least to check if this is the case, would be to edit lmhosts file to map the computer name of each one its IP address (both in the client and server).
See a somewhat confused post i made back then:
http://groups.google.com/group/microsoft.public.sqlserver.server/browse_thread/thread/2c246bd2afc7c4d9