vendredi 31 juillet 2015

Not able to start sql server service after moving the data files to new location

I have moved the data files to new location but while moving I have given the wrong data file name. So it is throwing error

A file activation error occurred. The physical file name 'D:\Programfiles\Microsoft Sql server\MSSQL2008\Data\MSDBLog.ldf' may be incorrect. Diagnose and correct additional errors, and retry the operation.

FCB::Open failed: Could not open file D:\Programfiles\Microsoft Sql server\MSSQL2008\Data\modellog.ldf for file number 2. OS error: 5(Access is denied.).

these were the errors I was getting after the data file movement.

Please suggest me what should be done to run the sql server service.

How to check srttotime value and database value in laravel

Hi I have table wys_attendances(id,t_id, t_date,t_month_t_year,t_attend)

Iam trying to fetch one full month attendances from wys_attendance table like pivot table format. rows base teacher name and column base full month day (1/2/2015,2/2/2015....28/2/2015) i got this format output by using this code my controller $teacher = WysTeacher::all(); $dayCount = date('t', strtotime('01-'. $amonth . '-' . $ayear)); for($i = 1; $i <= $dayCount; $i++)

my view .blade.php

<tr class="tbl-head"> <td>Teacher Name</td> @for($i = 1; $i <= $dayCount; $i++) <td>{{$i}}</td> @endfor </tr> @foreach($teacher as $teachers) <tr>
<td>{{$teachers->tname}}</td> @endforeach </tr>

then iam try to display attendance(present() p/absend(a))below in column date and also corrseponding teachername by usinf this code

@foreach($attendance as $attendances)
                  @if($teachers->id == $attendances->t_auserid)  
                  @if($attendances->t_attendance == 1)
                  <td><font color="green">p</font></td>
                  @elseif($attendances->t_attendance == 0)
                  <td><font color="red">a</font></td>    
                  @endif
                  @endif
 @endforeach

its work fine ,but one problem ,the problem is attendance marked at not corresponding date.

if1/2/2015 date not in database and 2.2/2015 is in database all present(p). but display in view page column 1/2/2015 below marked p value and 2/2/2015 below marked next day attendance .

how to check month date and database value is correct??and display attendance at correcponding date below.

Single Select SQL Statement for 2 different Values

I have a SQL Server table with a column called Category. In my user interface, I have a dropdown list of the category. User can select a category and click on a Search button to filter the results by the category. In the dropdown, the first option is blank. Means if the user wants to see all records from all categories, he can select blank.

In my SQL Select I have 2 statements for this

IF @Catg IS NULL
Begin
    Select * 
    From Table
End
Else
Begin
    Select * 
    From Table 
    Where Catg = @Catg
End

The Catg column in the table will have either a NULL or a category. Is this possible to do in a single SQL statement?

Join two tables to get matching records and unmatched records from Table 1

Scenario: I have 2 tables namely Coverage and Product

Coverage Table: CId,CName,CType,CMessage,CDate,CoverageProductId

Product Table: PId,CName,CType,CMessage,PDate,CoverageProductId

By using CoverageProductId i am relating 2 tables.

I need to get 3 columns CName,CMessage and CoverageProductId from both tables

Condition Below,

  • Get 3 columns values from Product table if both table CoverageProductId matches.
  • Get 3 columns values from Coverage table if both table CoverageProductId not matches.

My query is below in MS sql server

SELECT Distinct C.CoverageProductID
,C.CName
,C.CType
FROM Coverage C
INNER JOIN Product P
ON C.CoverageProductID!=P.CoverageProductID
UNION
SELECT Distinct P.CoverageProductID
,P.CName
,P.CType
FROM Coverage C
INNER JOIN Product P
ON C.CoverageProductID=P.CoverageProductID

But the result is not as expected and it returns duplicate values.

T-SQL: Splitting a OTLT table into many-to-many relationship

I have an entity framework application. There is a table that is starting to cause a lot of problems, mostly because it doesn't follow EF conventions:

old table

The two important columns are RequestType and RequestDetailId. Each type of request has its own identity column. Since those identities can overlap across tables, there is a RequestType field to uniquely associate an approval to a request.

I am planning on replacing this "One True Lookup Table" with an Approval table and a separate many-to-many table for each request table, linking the request to the approval:

new table

I have a couple of requests already pointing to this new approval table and I like how it is working within EF. However, I am having a hard time migrating from the old table to the new tables. So far, I have been looping through the old data with a cursor, inserting into the new Approval table and using the identity (SELECT SCOPE_IDENTITY()) to insert into the many-to-many table. I need a cursor because I need to keep track of the approval identity value for each new approval record, so I can populate the many-to-many table with it.

I was curious if someone knew a way to do the two inserts without requiring a cursor. Cursors are fine, but they are hard to read.

One thought was to temporarily add a Request ID field to the Approval table, inserting the approval with the request ID, then joining that information to the old table to populate the many-to-many table. After the two inserts, I would drop the request ID column. I don't like the idea of adding a nullable request ID column to an existing table just to do a migration.

I was curious if someone could think of a way to split the old lookup table into the new approval/many-to-many tables without using a cursor.

IIS 8.5 Web.config for named SQL instance on alternate port

I recently upgraded to Windows Server 2012 from 2003. It was a big IIS jump from 6 to 8.5. I cannot seem to get a named SQL instance on an alternate port to work in my ASP.net 4.0 website. The connection string I am using is as follows:

When the website tries to load in the browser, I get the following error:

[HttpException (0x80004005): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - No connection could be made because the target machine actively refused it.)]

We've checked firewall settings to no avail. Is the syntax correct in the above example? I've done numerous searches and found examples of people using ip:port\instance and ip\instance;port; but both of those give syntax errors.

I need some confirmation on the correct syntax for the Web.config file. Any help is greatly appreciated, thanks!

SQL Date Queries

Please help me understand the SQL Select statement below:

Select DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 1, 0)

The 0s are throwing me off.

Clustered/nonclustered primary key dilemma

Suppose we'd have to define optimal indexing for Stackoverflow questions. But let's not take the schema of the actual Posts table, let's just include those columns that are actually relevant:

create table Posts (
    Id int not null
        identity,
    PostType tinyint not null,
    CreationDate datetime not null
        default getdate(),
    LastActivityDate datetime not null
        default getdate(),
    Title nvarchar(500) null, -- answers don't have titles
    Body nvarchar(max) not null,
    ...
)

I've added Id to be identity even though Data Stackexchange shows that none of the tables has a primary key constraint on them, nor identity columns. There are many just unique/non-unique clustered/non-clustered indices.

Usage scenarios

So basically two main scenarios for posts:

  1. They're chronologically displayed in descending order by their LastActivityDate column (or maybe LastEditDate that I haven't included above as it's not so important)
  2. They're individually displayed on question details
  3. Answers are displayed on question details page in votes order (ScoreCount column not part of my upper code)

Indexing optimization

Which indices would be best created on above scenarios especially if we'd say that #1 is the most common scenario so it has to work really fast.

I'd say that one of the better possibilities would be to create these indices:

-- index 1
alter table Posts
add primary key nonclustered (Id);

-- index 2
create clustered index IX_Posts_LastActivityDate
on Posts(LastActivityDate desc);

-- index 3
create index IX_Posts_ParentId
on Posts(ParentId, PostTypeId)
include (ScoreCount);

This way we basically end up with three indices of which the second one is clustered.

So in order for #1 to work really fast I've set clustered index on LastActivityDate column, because clustered indices are especially great when we do range comparison on them. And we would be ordering questions chronologically newest to oldest hence I've set ordering direction and also included type on the clustered index.

So what did we solve with this?

  1. scenario #1 is very efficiently covered by index 2 as it's clustered and fully covered; we can also easily and efficiently do result paging;
  2. scenario #2 is somewhat covered with unique index 1 (to get the question) and non-unique index 3 to get all related answers ordered by ScoreCount; and if we decide to chronologically order answers that's also covered with index 2;

Question 1

SQL internals are such that SQL implicitly adds clustered key to nonclustering index so it can locate records in the row store.

  • if clustering index is unique, than that's the key that will be added to nonclustering indices, and
  • if clustering index is non-unique, SQL supposedly generates its own UniqueId and uses that

Since I've also added a nonclustered primary key on the table (which must by design be unique), I would like to know whether SQL will still supply its own unique key on clustered non-unique index or will it use nonclustered primary key to uniquely identify each records instead?

Question 2

So if primary key isn't used to locate records on row store (clustered index) does it even make sense to actually create a PK? Would in this case be better to rather do this?

create unique index UX_Posts_Id
on Posts(Id);
-- include (Title, Body, ScoreCount);

It would be great to also include commented out columns, but then that would make this index inefficient as it will be worse in caching... Why I'm asking whether it would be better to create this index instead of a primary key constraint is because we can include additional non-key columns to this index while we can't do the same when we add a PK constraint that internally generates a unique index...

Question 3

I'm aware that LastActivityDate changes which isn't desired with clustered indices, but we have to consider the fact that this column is more likely to change for some time before it becomes more or less static, so it shouldn't cause too much index fragmentation as records will mostly be appended to the end whenever LastActivityDate changes. Index fragmentation would never happen because some new record would be inserted into some old(er) page. Most modifications will happen on the last page.

So the question is whether these changes can be harmful as LastActivityDate isn't the best candidate for clustering index key:

  • it's not unique - although one could argue about this, especially if we'd change datetime to datetime2 and use higher precision function sysdatetime()
  • it's narrow - pretty much
  • it's not static - but I've explained how it changes
  • it's ever increasing

What is the solution when i want to update list data from Application to exists large records in SQL server (more then 800million records)

Please tell me how to update list data from Application to exists large records in SQL server (more then 800million records).

This mean : i will foreach my List data --> then [select record by id from table in SQL] then if exist record i will update record from Application to SQL server. Because the database very large then 1 record want to be updated will find more than 800million records in SQL--> 1*800million--> so i want to update 100 record then --> 100*800million.

Please help me the best solution to solve this prolem. Thank you so much!

Publishing MVC project Via FTP via Visual Studio

I am trying to copy my project to server which does not have web deploy. (tsohost- if am wrong). So the only option i have left is FTP. Somehow when i do this with VS 2013 it skips my database (mdf file) and few folders in Content. The page works after publish but functionally based on database is of course gone. The question is whether there is some way around this to deploy full solution via FTP? It's MVC 5 working on .NET 4.5 on Windows 2012 Thanks for any help

SQL Query taking long time with STUFF function

Example Dataset:

ID  seat    code
15098   1   AA21
15098   2   AA21
15105   1   AA21
15105   1   DD15
15105   1   NN60
15196   1   AA21
15196   2   DD50
15196   2   DD51
15209   1   AA21
15209   3   AA21
15209   2   CC50
15209   1   DD01
15209   3   DD01
15210   1   AA21
15210   2   AA21
15210   3   AA21
15210   1   DD21
15210   2   DD21
15210   3   DD21
15211   1   CC51
15211   1   DD20
15212   1   AA21
15212   1   DD03

and Desired Result is:

ID  seat    Codes
15098   1    AA21
15098   2    AA21
15105   1    AA21, DD15, NN60
15196   1    AA21
15196   2    DD50, DD51
15209   1    AA21, DD01
15209   2    CC50
15209   3    AA21, DD01
15210   1    AA21, DD21
15210   2    AA21, DD21
15210   3    AA21, DD21
15211   1    CC51, DD20
15212   1    AA21, DD03


Example Dataset table query:

CREATE TABLE #Temp(
ID varchar(50),
seat varchar(50), 
code varchar(150))

INSERT INTO #Temp VALUES ('15098', '1', 'AA21');
INSERT INTO #Temp VALUES ('15098', '2', 'AA21');
INSERT INTO #Temp VALUES ('15105', '1', 'AA21');
INSERT INTO #Temp VALUES ('15105', '1', 'DD15');
INSERT INTO #Temp VALUES ('15105', '1', 'NN60');
INSERT INTO #Temp VALUES ('15196', '1', 'AA21');
INSERT INTO #Temp VALUES ('15196', '2', 'DD50');
INSERT INTO #Temp VALUES ('15196', '2', 'DD51');
INSERT INTO #Temp VALUES ('15209', '1', 'AA21');
INSERT INTO #Temp VALUES ('15209', '3', 'AA21');
INSERT INTO #Temp VALUES ('15209', '2', 'CC50');
INSERT INTO #Temp VALUES ('15209', '1', 'DD01');
INSERT INTO #Temp VALUES ('15209', '3', 'DD01');
INSERT INTO #Temp VALUES ('15210', '1', 'AA21');
INSERT INTO #Temp VALUES ('15210', '2', 'AA21');
INSERT INTO #Temp VALUES ('15210', '3', 'AA21');
INSERT INTO #Temp VALUES ('15210', '1', 'DD21');
INSERT INTO #Temp VALUES ('15210', '2', 'DD21');
INSERT INTO #Temp VALUES ('15210', '3', 'DD21');
INSERT INTO #Temp VALUES ('15211', '1', 'CC51');
INSERT INTO #Temp VALUES ('15211', '1', 'DD20');
INSERT INTO #Temp VALUES ('15212', '1', 'AA21');
INSERT INTO #Temp VALUES ('15212', '1', 'DD03');

I am using below query as a part of my SSRS report stored procedure to get the result but it is taking too long to run as my original dataset is more than a 100000 rows. Is there any other efficient way to get the result.

SELECT 
 SS.ID
,SS.seat
,STUFF((SELECT ', ' + CAST(LTRIM(RTRIM(CR.Code)) AS VARCHAR(10)) [text()]
        FROM #Temp CR 
        WHERE CR.ID = SS.ID and CR.seat = SS.seat
        FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,2,' ') Codes
FROM #Temp SS
GROUP BY SS.ID, SS.seat

How to use boolean fuction in Where on QueryOver API

Im trying to use the SQL function CONSTAINS to filter some data on QueryOver API.

The main issue is i cant use SqlFunction in where clause, this does not compile, because a ICriterion is needed.

var result = Session.QueryOver<Individual>()
    .Where(Projections.SqlFunction(
        "FullTextContains", NHibernateUtil.Boolean,
        Projections.Property<Individual>(x => x.LastName),
        Projections.Constant("something")))
        .List();

I tried to match it to a TRUE constant, but when the query is executed it generates syntax error, because the CONSTAINS function cant be used with equals operator.

var result = Session.QueryOver<Individual>()
    .Where(Restrictions.Eq(Projections.SqlFunction(
        "FullTextContains", NHibernateUtil.Boolean,
        Projections.Property<Individual>(p => p.LastName),
        Projections.Constant("something")), true))
        .List();

How can i use a boolean sql function directly in where expression on QueryOver API?

Select statement against a particular table taking forwever

I have been trying to troubleshoot this problem for a while and at this point, I have no further clues. The problem occurs only in a specific table in an SQL Server database:

Symptoms:

SELECT TOP 1000 * FROM Particular_Table /* works fine */
SELECT TOP 1000000 * FROM Particular_Table /* still works fine */
SELECT * FROM Particular_Table /* statement takes forever to execute */

It's a simple plain SELECT query, no joins, and other tables in the same database do not manifest these symptoms.

My observation is that the query gets close to the end, but never completes. The table is not huge, it has about 800,000 records.

I do not have admin access to the server and I am unable to check error logs, but I can run any query.

Any suggestion on how to locate the root of the problem would be much appreciated.

There is no option of audit in security... SQL Server 2014 ...How to enable audit option in SQL server 2014

Please see the below image there is no option about audit in databaseenter image description here

Storing Password in SSSI Package

I have an SSIS Package which uses to connect Oracle. I used Oracle Provider for OLEDB connection manager in SSIS to setup. I have providing my server name, user name and password, selected the check box "Allow Saving Password". It is running fine on my machine but when I give a copy to another developer, he fails to run as he gets null password error. Is there a way to save password in SSIS Package so that we don't need to worry about that? Thanks

SQL Server Agent run powershell file not found

I created a SQL Server Agent job and here is the job detail.

  • The job owner is my windows domain login.
  • The type is OS (cmdExec)
  • Run as SQL Server Agent Service Account
  • Command:

    powershell.exe -executionpolicy bypass -file "D:\MyFolder\myFile.ps1".

When I ran the job it returned an error stating "D:\MyFolder\myFile.ps1" does not exist.

When I run the same command from cmd prompt it works find.

My question is what can I do to make SQL Server Agent Service Account "see" the file?

Thanks,

SQL Server 2014 ShowPlanXML hyperlink crashes ssms

On SQL Server 2014, my client crashes after running a DMV query that shows a query plan. An example of the code:

SELECT TOP 10 
DB_NAME(qt.dbid) as dbname, 
OBJECT_NAME(qt.objectid) 
spname, 
qs.execution_count,
qs.total_logical_reads, 
qs.last_logical_reads,
qs.total_logical_writes, 
qs.last_logical_writes,
qs.total_worker_time,
qs.last_worker_time,
qs.total_elapsed_time,
qs.last_elapsed_time,
qs.last_execution_time,
qp.query_plan
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
WHERE qt.dbid not in (1,2,3,4,18) --system & distribution databases
ORDER BY qs.last_logical_writes DESC, execution_count DESC

The result set for the query_plan column is a hyperlink that displays the actual query plan. Once I click on a row in the query_plan column, the ssms client crashes.

French Characters in SQL Text field to UTF - 8

I have some french characters stored in a text column in Sql Server(not ntext but text). When I display this on html i get some funny question mark characters in the string.

Even if I convert the text to nvarchar(max) and display on html I still get the same error.

How do I convert the french characters in the text field to UTF-8 correctly? I am using C#, .NET 4.5.

Thank you, GMAT

Data Factory Error on On-Prem SQL to Azure SQL Test

I'm attempting to do a simple test of copying data from an on-prem database to an Azure database. The error message I receive is on the Azure dataset:

Invalid parameter 'ConnectionString' provided to copy activity. This could be caused by the mismatch between the information in encrypted credential and the information in connection string. If connection string is updated, generate the encrypted credential again and update the LinkedService.

I had Azure build their sample pipeline and pointed the Azure db to the same one I'm using below and then copied the syntax and even used the linked service it generated for the same Azure database, but I still can't seem to resolve it.

Here is the code for the linked service:

{
"name": "AzureSqlLinkedService",
"properties": {
    "description": "",
    "hubName": "onpremcnodsdf_hub",
    "type": "AzureSqlDatabase",
    "typeProperties": {
        "connectionString": "Data Source=tcp:abc123.database.windows.net,1433;Initial Catalog=TestDatabase;Integrated Security=False;User ID=userid;Password=**********;Connect Timeout=30;Encrypt=True"
    }
}

The dataset:

{
"name": "AzureSQLDatasetTemplate2",
"properties": {
    "structure": [
        {
            "name": "StoreID",
            "type": "String"
        },
        {
            "name": "Nickname",
            "type": "String"
        },
        {
            "name": "Address",
            "type": "String"
        },
        {
            "name": "City",
            "type": "String"
        },
        {
            "name": "State",
            "type": "String"
        },
        {
            "name": "ZipCode",
            "type": "String"
        },
        {
            "name": "PhoneNumber",
            "type": "String"
        },
        {
            "name": "EntityID",
            "type": "String"
        },
        {
            "name": "Owner",
            "type": "String"
        },
        {
            "name": "Email",
            "type": "String"
        },
        {
            "name": "ModifiedDate",
            "type": "String"
        },
        {
            "name": "ModifiedBy",
            "type": "String"
        }
    ],
    "published": false,
    "type": "AzureSqlTable",
    "linkedServiceName": "AzureSqlLinkedService",
    "typeProperties": {
        "tableName": "cStoreTest"
    },
    "availability": {
        "frequency": "Day",
        "interval": 1
    }
}

And the pipeline:

{
"name": "ADFTutorialPipelineOnPrem",
"properties": {
    "description": "This pipeline has one Copy activity that copies data from an on-prem SQL to Azure Sql",
    "activities": [
        {
            "type": "Copy",
            "typeProperties": {
                "source": {
                    "type": "SqlSource",
                    "sqlReaderQuery": "SELECT * FROM CNIT.dbo.cStore"
                },
                "sink": {
                    "type": "SqlSink",
                    "sqlWriterStoredProcedureName": "spcStoreTestInsert",
                    "sqlWriterTableType": "cStoreTestType",
                    "writeBatchSize": 100,
                    "writeBatchTimeout": "01:00:00"
                }
            },
            "inputs": [
                {
                    "name": "SQLServerDatasetTemplate"
                }
            ],
            "outputs": [
                {
                    "name": "AzureSQLDatasetTemplate2"
                }
            ],
            "policy": {
                "timeout": "01:00:00",
                "concurrency": 1,
                "executionPriorityOrder": "NewestFirst",
                "style": "StartOfInterval"
            },
            "scheduler": {
                "frequency": "Day",
                "interval": 1
            },
            "name": "CopyFromOnPremtoAzure",
            "description": "Copy data from on-prem SQL server to Azure SQL"
        }
    ],
    "start": "2014-05-01T00:00:00Z",
    "end": "2014-05-05T00:00:00Z",
    "isPaused": false,
    "hubName": "onpremcnodsdf_hub"
}

I'm very new to Azure so any insight you may have would be greatly appreciated.

Thanks!

Year format in Oracle - Datastage

guys. I'm facing some problems with a year format on Datastage. I have a Oracle procedure that returns me a Date datatype column. I have a business flow job that write this date in a dataset that will be the initial step for another business flow job, consulting another procedure.

I need to format my date, but i don't know how. The Oracle returned value for this date its like '01-JAN-15' in format dd-mm-yy. The Datastage understand this date like '0015-01-01' in format yyyy-mm-dd. Then, when the dataset file is consumed by the other job, i got a "Datetime field overflow" error. I need to set the correct year, but i've tried everything, like Oconv() functions but doesn't helped at all.

Does anyone know how to help me?

Thank you a lot, guys.

Link Table A Column NAME with Table B data MSSQL Server

I am trying to link(join) the NAME column from PBXSTATION to the PBXDATA table. I also want it to be able to match the NAME with the EXT(extension) column? EXTENSION in PBXSTATION is the same as EXT in PBXDATA. I will rename EXT to EXTENSION, that way the fields match. Any help would be great. My MSSQL Server is a little hazy. Thank you!

enter image description here

Reading Excel files into SQL Server not using OLEDB/ODBC

Is there a way to read Excel 2010/2013 files natively ?

We are importing Excel files into SQL Server and have come across a specific issue whereby it looks as though the Excel driver decides the type of a destination data column depends upon testing the contents of only the first 65K odd rows.

This has only just started happening within the past 3 weeks, before then we had managed to convince Excel of the error of its ways by a simple registry hack that forced it to read the entire set of rows.

The problem is that we have some datasets that contain, say 120,000 rows and these may have all numeric values for the first 80,000, then it will have some non-numeric yet vital information that we wish to retain.

Yes, the data is not correctly typed, we know.

Because the source data type has been determined by the Excel driver to be a float it promptly turns all our non-numeric values into NULLs - not very useful.

If there was some other way to read an Excel file not using the standard ODBC/OLEDB drivers that might help.

We have tried saving it into various other formats before importing but of course all these exports use the Excel driver which has the problem.

I think the closest we have got is to save it as XML (which is frankly huge at 800MB) and then shred it using standard xpath queries and some pretty dodgy workarounds to handle no doubt well-formed but still tricky variations on how column data is represented.

Edit: changed title to more closely reflect the issue

Fill in missing values in a table in SQL

This is how my table looks like..i want to fill in the missing week numbers in 2015 and 2016,say 1-52 weeks in 2015 and again 1-52 for 2016 for the same product and in that particular location.

row product loc     year    week    quantity
1   A       X      2015      2        30
2   A       X      2015      4        34
3   A       X      2015      5        45
4   A       X      2015      6        56
5   A       X      2015      7        324
6   A       X      2015      8        56
7   A       X      2015      9        67
8   A       X      2016      1        34
9   A       X      2016      2        76
10  A       X      2016      3        45

output would be like

row product loc     year    week    quantity
1   A       X      2015      1        0
2   A       X      2015      2        30
3   A       X      2015      3        0
4   A       X      2015      4        34
5   A       X      2015      5        45
6   A       X      2015      6        56
7   A       X      2015      7        324
8   A       X      2015      8        56
52  A       X      2015      52        0
53  A       X      2016      1        34
54  A       X      2016      2        76
55  A       X      2016      3        45
106 A       X      2016      53       0 ...

Updating the table with values did not work and also tried cross apply..

WPF query dont seem appropriate

i have this application in which report is not working, i am actually a php developer and i can understand the select * from table like query but linq query is new to me..

But even in linq query there is a join concept but i am not seeing any joins in this query so i am wondering is ther anything wrong with this query or is this normal in WPF to use query like that.

                var query = from t in dc.TransectionsRemittenances
                            from c in t.CustomerAccounts
                            from b in t.Beneficiaries
                            from bank in b.BeneBankAccounts
                            where t.AgentId == int.Parse(agentId)
                            where t.GbBranchId == GlobalClass.GbBranchID
                            where t.Date == givenDate
                            select new { t, c, b, bank };

The Actual Code is like This.

private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            string agentName = string.Empty;
            try
            {
                DateTime givenDate = DateTime.ParseExact(tbDate.Text, "M/d/yyyy", CultureInfo.InvariantCulture);

                if (cmbAgents.SelectedIndex >= 0)
                {
                    agentId = ((DataRowView)cmbAgents.SelectedItem).Row.ItemArray[0].ToString();
                    agentName = ((DataRowView)cmbAgents.SelectedItem).Row.ItemArray[1].ToString();
                    //MessageBox.Show(agentId);
                    //------------------------LOAD REPORT--------------------------//

                    Microsoft.Reporting.WinForms.ReportDataSource reportDataSource1 = new Microsoft.Reporting.WinForms.ReportDataSource();
                    RMSDatabase2DataSet dataset = new RMSDatabase2DataSet();

                    dataset.BeginInit();

                    DataClassesDataContext dc = new DataClassesDataContext();
                    DataSet1.AgentFaxDSDataTable dt = new DataSet1.AgentFaxDSDataTable();

                    if (GlobalClass.GbBranchID != 12)
                    {
                        var query = from t in dc.TransectionsRemittenances
                                    from c in t.CustomerAccounts
                                    from b in t.Beneficiaries
                                    where t.AgentId == int.Parse(agentId)
                                    where t.GbBranchId == GlobalClass.GbBranchID
                                    where t.Date == givenDate
                                    select new { t, c, b};

                        foreach (var d in query)
                        {
                                dt.Rows.Add(d.t.ReceiverCurrency, d.t.ReceivedAmount, d.t.Date,
                                d.c.Name, d.b.Name, d.b.FName, d.b.City, d.b.Address);//, "", "", "", "");
                        }

                    }
                    else
                    {
                        var query = from t in dc.TransectionsRemittenances
                                    from c in t.CustomerAccounts
                                    from b in t.Beneficiaries
                                    from bank in b.BeneBankAccounts
                                    where t.AgentId == int.Parse(agentId)
                                    where t.GbBranchId == GlobalClass.GbBranchID
                                    where t.Date == givenDate
                                    select new { t, c, b, bank };

                        foreach (var d in query)
                        {
                            if (d.t.BeneSource == null)
                            {
                                dt.Rows.Add(d.t.ReceiverCurrency, d.t.ReceivedAmount, d.t.Date,
                                d.c.Name, d.b.Name, d.b.FName, d.b.City, d.b.Address, "", "", "", "");
                            }
                            else
                            {
                                dt.Rows.Add(d.t.ReceiverCurrency, d.t.ReceivedAmount, d.t.Date,
                                d.c.Name, d.b.Name, d.b.FName, d.b.City, d.b.Address, " (Bank: " + d.bank.BankName + ",",
                                " AccNo-" + d.bank.BankAccountNo + "-", " BCode-" + d.bank.BranchCode, ", " + d.bank.Address + ")");
                            }
                        }
                        //query.ToArray().
                    }

                    reportDataSource1.Name = "DataSet1"; //Name of the report dataset in our .RDLC file
                    reportDataSource1.Value = dt;


                    this._reportViewer.LocalReport.DataSources.Clear();
                    this._reportViewer.LocalReport.DataSources.Add(reportDataSource1);
                    this._reportViewer.LocalReport.ReportEmbeddedResource = "RMS.rptRemittances.rdlc";

                    ReportParameter[] param = new ReportParameter[2];
                    param[0] = new ReportParameter("para_agent", agentName.ToString());
                    param[1] = new ReportParameter("para_forDate", givenDate.ToString("d/M/yyyy"));

                    this._reportViewer.LocalReport.SetParameters(param);

                    _reportViewer.RefreshReport();
                }
            }
            catch (Exception ex)
            {
                string messageBoxText = "Enter Date Formate is incorrect, it must be 'MM/DD/YYYY'.\n\n" + ex.Message;
                string caption = "Error";
                MessageBoxButton button = MessageBoxButton.OK;
                MessageBoxImage icon = MessageBoxImage.Error;
                MessageBox.Show(messageBoxText, caption, button, icon);

            }
        }

can anyone tell if query is ok and if its ok. then how its working i mean joins, inner join or left join etc. Plus what is the name of this query if its not linq query what should i look for on internet..

As i am getting no problem from this query in application developed by previous developer of my company. But i am also not getting any data thats why i am trying to check this query is ok and want to run it in MSSQL to see if there is any result generating from it.. BUt nt sure wht to do with the joins??

T-SQL - Deduplicate large table

Sorry if this has already been asked. I see a lot of similar questions but none exactly like this one.
I am trying to de-dup a large set (about 500 M) records:

Sample data:

CUST_ID  PROD_TYPE  VALUE  DATE
------------------------------------
1        1          Y      5/1/2015 *
1        2          N      5/1/2015 *
1        1          N      5/2/2015 *
1        2          N      5/2/2015 
1        1          Y      5/3/2015 *
1        2          Y      5/3/2015 *
1        1          Y      5/6/2015 
1        2          N      5/6/2015 *

By CUST_ID and PROD_TYPE, I need to retain the initial records as well as any records having a changed VALUE (the records with the asterisks). There can sometimes be gaps between the dates. There are around 5M unique CUST_ID's.

Any help would be greatly appreciated.

Error with linked server using Microsoft.Jet.OLEDB.4.0

I started at this company, and the jobs were pretty complex and undocumented. One of the procs checks on txtfiles that SSIS creates by using a linked server that uses Microsoft.Jet.OLEDB.4.0 and points to its own C drive. Using that, the job does a count on each table, and compares it to its totals. Maybe unnecessarily complex.

It was working properly till last Friday, when I started getting the error:

OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "textserver"
returned message "Unspecified error". Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider
"Microsoft.Jet.OLEDB.4.0" for linked server "textserver".

The query used is:

SELECT COUNT(*) FROM textserver...[textfile#txt]

I've tried rebooting the server, and recreating the linked server to no avail.

Has anyone seen this issue before?

Create SQL View With Entity Framework 6 Code First

I am new to Entity Framework 6 Code First and am trying to perform what I thought would be a simple task. I want to create a SQL View and then have an Entity in my database context that I can use to query the view.

I have tried articles such as this but the key difference in my case is that the SQL View is not an existing view coming from another existing database.

I examined the proposition made in this article but it seems like overkill to me that I would need to create some extension methods to do something as simple as create a view/entity combo and use it in my database context.

Am I missing something? I know it would be much easier if I weren't using Code First but please keep in mind it's Code First and I am trying to create a view, not reuse one from an existing database.

How to add a filter to find all project with a specific user

I have the following structure on SQLFiddle that has been created by others who helped me (Using two columns in a PIVOT):

CREATE TABLE Project (
  Id int,
  Name VARCHAR(50),
  CONSTRAINT PK_Project PRIMARY KEY (Id));


CREATE TABLE [User] (
  Id int,
  Name VARCHAR(50),
  Register int,
  CONSTRAINT PK_User PRIMARY KEY (Id));

CREATE TABLE ProjectMember (
  Project_Id int,
  User_Id int, 
  MemberType tinyint,
  CONSTRAINT PK_ProjectMember PRIMARY KEY(Project_Id, User_Id),
  CONSTRAINT FK_ProjectMember_Project FOREIGN KEY(Project_Id) REFERENCES Project(Id),
  CONSTRAINT FK_ProjectMember_User FOREIGN KEY(User_Id) REFERENCES [User](Id));



 INSERT INTO Project(Id, Name) VALUES(1, 'Project 1');
 INSERT INTO Project(Id, Name) VALUES(2, 'Project 2');
 INSERT INTO Project(Id, Name) VALUES(3, 'Project 3');
 INSERT INTO Project(Id, Name) VALUES(4, 'Project 4');
 INSERT INTO Project(Id, Name) VALUES(5, 'Project 5');
 INSERT INTO Project(Id, Name) VALUES(6, 'Project 6');
 INSERT INTO Project(Id, Name) VALUES(7, 'Project 7');


 INSERT INTO [User](Id, Name, Register) VALUES(1, 'User 1', 23498374);
 INSERT INTO [User](Id, Name, Register) VALUES(2, 'User 2', 96849887);
 INSERT INTO [User](Id, Name, Register) VALUES(3, 'User 3', 6546884);
 INSERT INTO [User](Id, Name, Register) VALUES(4, 'User 4', 8489848);
 INSERT INTO [User](Id, Name, Register) VALUES(5, 'User 5', 4684854);
 INSERT INTO [User](Id, Name, Register) VALUES(6, 'User 6', 4849888);
 INSERT INTO [User](Id, Name, Register) VALUES(7, 'User 7', 84884446);
 INSERT INTO [User](Id, Name, Register) VALUES(8, 'User 8', 77554454);
 INSERT INTO [User](Id, Name, Register) VALUES(9, 'User 9', 77853997);

 INSERT INTO ProjectMember(Project_Id, User_Id, MemberType) VALUES(1, 1, 0);
 INSERT INTO ProjectMember(Project_Id, User_Id, MemberType) VALUES(1, 2, 1);
 INSERT INTO ProjectMember(Project_Id, User_Id, MemberType) VALUES(1, 3, 2);
 INSERT INTO ProjectMember(Project_Id, User_Id, MemberType) VALUES(1, 4, 2);
 INSERT INTO ProjectMember(Project_Id, User_Id, MemberType) VALUES(1, 5, 2);
 INSERT INTO ProjectMember(Project_Id, User_Id, MemberType) VALUES(3, 6, 0);
 INSERT INTO ProjectMember(Project_Id, User_Id, MemberType) VALUES(3, 5, 1);
 INSERT INTO ProjectMember(Project_Id, User_Id, MemberType) VALUES(4, 3, 0);
 INSERT INTO ProjectMember(Project_Id, User_Id, MemberType) VALUES(4, 4, 1);
 INSERT INTO ProjectMember(Project_Id, User_Id, MemberType) VALUES(4, 5, 2);

 INSERT INTO ProjectMember(Project_Id, User_Id, MemberType) VALUES(5, 7, 0);

 INSERT INTO ProjectMember(Project_Id, User_Id, MemberType) VALUES(6, 8, 1);

I have a new requirement from my client. He needs a filter to return all projects that have a MemberType = 2 and a specific User.Id, but the returned values doesn't need to include these values.

Example:

With this SQL statement:

SELECT  
    ProjectID              = P.Id, 
    ProjectName            = P.Name, 
    [UserType0 (Name)]     = MAX(CASE WHEN MemberType = 0 THEN u.Name END),
    [UserType0 (Register)] = MAX(CASE WHEN MemberType = 0 THEN Register END), 
    [UserType1 (Name)]     = MAX(CASE WHEN MemberType = 1 THEN u.Name END),
    (CASE WHEN MemberType = 2 THEN u.Name END) as [UserType2]
FROM Project AS P
LEFT JOIN ProjectMember AS PM ON P.Id = PM.Project_Id
LEFT JOIN [User] AS U ON PM.User_Id = U.Id 
GROUP BY P.Id, P.Name, PM.MemberType, U.Name

I get this value:

| ProjectID | ProjectName | UserType0 (Name) | UserType0 (Register) | UserType1 (Name) | UserType2 |
|-----------|-------------|------------------|----------------------|------------------|-----------|
|         1 |   Project 1 |           User 1 |             23498374 |           (null) |    (null) |
|         1 |   Project 1 |           (null) |               (null) |           User 2 |    (null) |
|         1 |   Project 1 |           (null) |               (null) |           (null) |    User 3 |
|         1 |   Project 1 |           (null) |               (null) |           (null) |    User 4 |
|         1 |   Project 1 |           (null) |               (null) |           (null) |    User 5 |
|         2 |   Project 2 |           (null) |               (null) |           (null) |    (null) |
|         3 |   Project 3 |           User 6 |              4849888 |           (null) |    (null) |
|         3 |   Project 3 |           (null) |               (null) |           User 5 |    (null) |
|         4 |   Project 4 |           User 3 |              6546884 |           (null) |    (null) |
|         4 |   Project 4 |           (null) |               (null) |           User 4 |    (null) |
|         4 |   Project 4 |           (null) |               (null) |           (null) |    User 5 |
|         5 |   Project 5 |           User 7 |             84884446 |           (null) |    (null) |
|         6 |   Project 6 |           (null) |               (null) |           User 8 |    (null) |
|         7 |   Project 7 |           (null) |               (null) |           (null) |    (null) |

But what I need is to return a single row per project that contains a user with a specific ID and MemberType = 2. How can I add this filter without changing the results like specified on Using two columns in a PIVOT?

SQL Select (Value A at max value B) and other computed values (avg/min/max)

I have some weather data stored in a SQL Server database. The relevant columns are

[SampleDate], [SampleDateTime], [WindSpeed_Avg_2MIN], [WindDir_AVG_2MIN]

and store data at 2 minute intervals. The code gives me a summary by day for a month

SELECT 
    [SampleDate], 
    Max([WindSpeed_Avg_2MIN]) as PeakWind, 
    Avg([WindSpeed_Avg_2MIN]) as AverageWind
FROM
   (SELECT 
        [SampleDateTime], 
        [WindSpeed_Avg_2MIN],
        [WindDir_AVG_2MIN] 
    FROM 
        WeatherData
    WHERE 
        ((DATEPART(mm,SampleDateTime) = @Month) 
        AND (DATEPART(yyyy,SampleDateTime) = @Year))) as tblA
GROUP BY 
    [SampleDate]
ORDER BY 
    [SampleDate]

Which yields

SampleDate  PeakWind    AverageWind
----------------------------------------
15/01/01    3.9         1.18587301587302
15/01/02    4.6         1.60222531293463
15/01/03    6.6         1.86013888888888

What I want is to add a column that would show the Wind Direction [WindDir_AVG_2MIN] for the row that had the PeakWind. So for 720 rows in a day, I've got the AVG and MAX of [WindSpeed_Avg_2MIN], and I want to show the discrete value for [WindDir_AVG_2MIN] for the row that has the MAX of [WindSpeed_Avg_2MIN]

Expected output:

SampleDate  PeakWind    AverageWind      WindDirAtPeakWind
----------------------------------------------------------
15/01/01    3.9         1.18587301587302 78
15/01/02    4.6         1.60222531293463 85
15/01/03    6.6         1.86013888888888 26

I can't seem to find the proper JOIN or sub query to get the result.

Any ideas?

DDL

CREATE TABLE [dbo].[WeatherData](
[SampleDateTime] [datetime] NULL,
[StationID] [smallint] NULL,
[SampleDate] [nchar](10) NULL,
[SampleTime] [nchar](10) NULL,
[WindSpeed_AVG_2MIN] [float] NULL,
[WindGust_AVG_2MIN] [float] NULL,
[WindDir_AVG_2MIN] [float] NULL,
[WindSpeed_AVG_10MIN] [float] NULL,
[WindGust_AVG_10MIN] [float] NULL,
[WindDir_AVG_10MIN] [float] NULL,
[AirTemp] [float] NULL,
[RelHumidity] [float] NULL,
[DewPoint] [float] NULL,
[Pyranometer] [float] NULL,
[Quantum] [float] NULL,
[AirPressure] [float] NULL,
[SnowLevel] [float] NULL,
[MeltedPrecip] [float] NULL,
[PW_Current] [char](10) NULL,
[PW_15MIN] [char](10) NULL,
[PW_60MIN] [char](10) NULL,
[PW_Vis] [float] NULL,
[Visibility] [float] NULL,
[CloudBase_1] [float] NULL,
[CloudBase_2] [float] NULL,
[CloudBase_3] [float] NULL,
[VerticalVis] [float] NULL,
[Batt_VDC] [float] NULL,
[BIT] [char](10) NULL
)

Example Data

SampleDateTime  StationID   SampleDate  SampleTime  WindSpeed_AVG_2MIN  WindGust_AVG_2MIN   WindDir_AVG_2MIN    WindSpeed_AVG_10MIN WindGust_AVG_10MIN  WindDir_AVG_10MIN
2015-01-31 23:59:06.000 100 15/01/31    03:03:58    16.1    19.3    25  15.6    19.3    27
2015-01-31 23:57:06.000 100 15/01/31    03:01:58    15.8    19.3    28  15.5    19.3    27
2015-01-31 23:55:05.000 100 15/02/01    02:59:58    9.8 10.9    16  8.8 11.1    19
2015-01-31 23:53:05.000 100 15/02/01    02:57:58    9.7 10.9    16  8.5 11.1    20

Recursive CTE - Employee with multiple Manager

I have a table like follow

+-----------+------------+
| ManagerID | EmployeeID |
+-----------+------------+
| MAN001    | BOY001     |
| MAN001    | BOY002     |
| MAN001    | BOY003     |
| MAN001    | BOY004     |
| MAN001    | BOY005     |
| BOY005    | KID001     |
| BOY005    | KID002     |
| BOY005    | KID003     |
| BOY005    | KID004     |
| MAN002    | BOY005     |
| MAN002    | BOY004     |
| BOY004    | KID001     |
| BOY004    | KID002     |
| BOY004    | KID003     |
| BOY004    | KID004     |
| KID002    | SOM001     |
| KID002    | SOM002     |
| KID002    | SOM003     |
+-----------+------------+

The main point is that MAN001 does not exists in EmployeeID, meaning MAN001 is top level. But BOY005 can work for MAN001 or MAN002 and more ... The same with KID00X CAN work with Any manager MAN00X or BOY00X.

It is also possible that KID001 KID002 KID003 KID004 may have an employee, eg KID002 has three Employee SOM001 SOM002 and SOM003 BUT BOY005 will never be an employee of KID because we know that BOY005 is the manager for KID.

The output that I would like to get is as follow, where the column E can grow as much as the data has.

+--------+--------+--------+--------+-------+
|   M1   |   E1   |   E2   |   E3   |  ...  |
+--------+--------+--------+--------+-------+
| MAN001 | BOY001 |        |        |       |
| MAN001 | BOY002 |        |        |       |
| MAN001 | BOY003 |        |        |       |
| MAN001 | BOY004 |        |        |       |
| MAN001 | BOY005 | KID001 |        |       |
| MAN001 | BOY005 | KID002 |        |       |
| MAN001 | BOY005 | KID003 |        |       |
| MAN001 | BOY005 | KID004 |        |       |
| MAN001 | BOY005 | KID002 | SOM001 |       |
| MAN001 | BOY005 | KID002 | SOM002 |       |
| MAN001 | BOY005 | KID002 | SOM003 |       |
+--------+--------+--------+--------+-------+

I tried to follow this basic simple recursive cte. But the example does not consider if an employee exists in multiple manager. http://ift.tt/QOJbrI

Also another different case with the blog post above is in my case Top level ManagerID simply don't exists in EmployeeID

WITH Emp_CTE AS (
SELECT EmployeeID, ManagerID
FROM Employee
WHERE ManagerID IS NULL
UNION ALL
SELECT e.EmployeeID, , e.ManagerID
FROM HumanResources.Employee e
INNER JOIN Emp_CTE ecte ON ecte.EmployeeID = e.ManagerID
)
SELECT *
FROM Emp_CTE

Thank you

What is wrong with my SQL Server query as it is not inserting the data in to table [on hold]

Here is my code

private void productsavebtn_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=SAJJAD-PC;Initial Catalog=hotel;Integrated Security=True;");

    try
    {
        con.Open();
        label1.Text = "Connection Successful";

        SqlCommand cmd1 = con.CreateCommand();
        cmd1.CommandText =( "INSERT INTO product (productname , productprice) VALUES ('" + productnametxtbox.Text + "','" + productpricetxtbox.Text + "')");

        try
        {
            cmd1.ExecuteNonQuery();
            label1.Text = "Data inserted successfully";
        }
        catch (Exception)
        {
            label1.Text = "Query execution failed";
        }
    }
    catch (Exception)
    {
        label1.Text = "Connection Failed";
    }
}

Until connection open it works fine but after that it is not executing the query and it's not even showing any error.

Split Table Into Two Separate Tables and Set New Primary Key as a Foreign Key

I have seen posts similar to what I need, but they all fall slightly short. I'm also not sure if what I need can be done. If it cannot be done, then any suggestions would be greatly appreciated.

I am reconstructing my database, and need to merge parts of three different tables into one. Currently I have three different types of tasks, let's call them DailyTasks, Reviews and Requests. All three tables have similar fields such as DateCreated, DateCompleted, EstimatedHours etc. I have created a parent table, called Tasks, which contains these common fields, and the other tables (DailyTasks, Reviews and Requests) only have fields that are specific to themselves. The child tables now also have a Foreign Key, TaskID, that points to the parent table. I believe this is standard database practice, correct me if I'm wrong.

Currently I am working in a test database, so I can pull the original data from the live database for testing purposes. I need to be able to pull the common fields from each table and place them in the parent table, while at the same time placing the new primary key into the TaskID column of the child table.

I would have like to of have used a join, but I don't believe I can insert into two tables that way while retrieving the Primary Key. My next thought if a join won't work is to use a cursor. Any help would be appreciated and I hope I've explained everything properly.

EDIT Here are the table's fields

TASKS (Parent)

  • TaskID (PK)
  • DateCreated
  • DateCompleted
  • DateDue
  • EstHrs
  • BaselineHrs
  • Notes
  • Priority
  • CreatedBy

DailyTasks (Child)

  • EngTaskID (PK)
  • TaskID (FK)
  • ProjectID
  • Description
  • AssignedTo

Requests (Child)

  • DrawingRequestID (PK)
  • TaskID (FK)
  • DrawingLink
  • PartNumber

Reviews (Child)

  • JobAuditID (PK)
  • TaskID (FK)
  • ItemNumber
  • CycleTime
  • ToolingRequirements

Get Paginated SQL Server Result AND total count in one query via Dapper?

If I had a User model that looks like this:

public class User
{
    public Guid Id { get; set; }
    public DateTime CreatedAtUtc { get; set; }
    public string Username { get; set; }
    public string Country { get; set; }
}

...and I'd perform a query which starts at a given row and fetches a limited amount of further rows (basically for paginating over the results) that looks like this:

var spaniards = connection.Query<User>(
                    "select * from Users where Country=@Country OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY",
                    new { Country = "Spain" }).ToList();

.. using Dapper(.Net), would it be possible to get that particular, limited result set AND the total count of rows in one single query and if so.. how?