dimanche 26 avril 2015

SQL Migration scripts from EDMX

I'm using DB-first approach. On every deployment I need to upgrade my the production DB with the new columns or changes to the existing columns.

I was looking at ways to generate a generic SQL script according to the EDMX the problem is that all script generation\ migration capabilities of Entity-Framework are for Code-First approach

Is there a way to create a SQL Script that would follow the following logic:

  1. if table not exist create the table (with no columns) if column X

  2. in table Y not exist add the column

    • if column exist check if types are the same if not alter the type (i know this can cause problems i'm still thinking on how to tackle that)
  3. if foreign key not exist create.

  4. if foreign key exist but should not drop it

any suggestion ?

Antlr4 mssql convert function grammar

I am looking for grammar for convert(datetime, convert(varchar(10), getdate(), 120))

I have following type of grammar defined,but it throws exception as below

getdate_fn: GETDATE LPAREN RPAREN;
varchar_fn: VARCHAR LPAREN INT RPAREN;
convert_fn: CONVERT LPAREN ( (DATETIME|varchar_fn) COMMA (convert_fn|getdate_fn) ) ((COMMA INT)?) RPAREN;

Exception:

MSSQL::convert_fn:1:34: mismatched input '10' expecting INT
MSSQL::convert_fn:1:49: mismatched input '120' expecting INT

Add incremental values in a single insert statement

The query below is not my actual query but a minimized version of it, as I cannot post the original one. However this explains what I want to do exactly:

Insert into TableA (BirthdateA, NameA)
Select BirthdateB,  (case when NameB is not null then NameB else "Desired Value" End) 
From TableB

"Desired Value" should be a dummy name in addition to an incremental value, for example "Dummy Name 1", "Dummy Name 2" So the final result would look like

TableB.Name     TableA.Name
John Smith       John Smith
Null             Dummy Name 1
Adam James       Adam James
John K.          John K.
Null             Dummy Name 2

Is that possible ?

Loading remote XML data into Azure SQL Server DB

I have managed to load remote (via a URL) XML data directly into a SQL Server DB instance on a local machine. I can then select the XML from the table.

I am attempting to replicate this is an Azure SQL DB instance.

Can anyone provide assistance with this? OLE is not available in WASD.

Presumably an Azure Runbook script to download the file to an Azure VM and then attempt to load into WASD?

Windows Azure SQL Database - WASD

Find the Row count of each value

I have table like

Name
A
B
B
C
C
C
A
A
B
B

I need Query to return output like

Name         count
A             1
B             2
C             3
A             2
B             2

I tried with rank(),dense_Rank().but i am not able to get output

How can I set a start and modified date with one SQL Update command?

I have a simple SQL Server table:

CREATE TABLE [dbo].[UserTest] 
(
    [UserTestId]    INT      IDENTITY (1, 1) NOT NULL,
    [UserId]        INT      NOT NULL,
    [ModifiedDate]  DATETIME NULL,
    [StartedDate]   DATETIME NULL
);

I set the modified date like this:

UPDATE UserTest
SET    ModifiedDate = @ModifiedDate
WHERE  UserTestId = @UserTestId
AND    UserId = @UserId

But is there a way I can also set the StartedDate in the same SQL to the @ModifiedDate if the StartedDate is NULL ?

SQL Server XQuery XML indexing

Using SQL Server 2008-

I have XML data stored in a column of my table which is the result of exporting some drawing info:

<layout>
    <config>
        <graphic_type>Box</graphic_type>
        <data_access>
        </data_access>
        <data>
            <dimension x="1" y="2" z="3" />
            <curve_info ir="-1.5" or="1.5" degree="0"/>
            <position x="4" y="5" z="6" />
            <rotation x="7" y="8" z="9" />
            <color>FFD3D3D3</color>
            <is_position_relative>false</is_position_relative>
        </data>
    </config>
    <config>
        ...
    </config>
</layout>

Where the number of to draw individual pieces is unknown. Currently if I wanted to do something like move the entire drawing 100 units along the X-axis, I have SQL code like:

SET @xTrans = 100
UPDATE TableName
SET xmlColumn.modify('replace value of (//data/position/@x)[1] with sql:variable("@xTrans")')
SET xmlColumn.modify('replace value of (//data/position/@x)[2] with sql:variable("@xTrans")')
SET xmlColumn.modify('replace value of (//data/position/@x)[3] with sql:variable("@xTrans")')
...
SET xmlColumn.modify('replace value of (//data/position/@x)[20] with sql:variable("@xTrans")')

And I essentially do that an arbitrary number of times because I don't know how many nodes actually exist in each drawing. I am fairly new to SQL, and even more so to XQuery, but is there a better way to go about this problem?

To be more extensible, the next problem I have is when Devices are drawn on top of this model, they were originally drawn in 2d before being exported to xml files, and so they take on the height value (happens to be the Y-axis in my case) of the first section of the drawing, when the devices X and Z coordinates potentially place it at the end of the entire drawing. This causes some devices to be floating either above or below the models. The only thing I could think to write for this problem is something like:

-- Determine if moving along X or Z axis by Y rotation
-- If its the Z-axis, find the range that section covers with position+dimension
    -- @range = (///position/@z)[1] + (///dimension/@z)[1]
-- See if the device falls in that range
    -- If (///position/@z)[1] < device position @z < @range
-- Then we need the rotation of that box in the Z-axis
-- to calculate the height change for the device

But this would involve having to copy and paste that code ~15 times (I'm not sure what the largest number of components a model could have, I have seen 6 on the current project) and changing the index [1] which seems extremely inefficient.

The device XML layout is exactly the same as the model, just with a different value for .

SQL intersect with group by

Given these two tables/sets with different groups of items, how can I find which groups in set1 span across more than a single group in set2? how can I find the groups in set1 which cannot be covered by a single group in set2?

e.g. for tables below, A (1,2,5) is the only group that spans across s1(1,2,3) and s2(2,3,4,5). B and C are not the answers because both are covered in a single group s2.

I would prefer to use SQL (Sql Server 2008 R2 available).

Thanks.

set1                            set2
 +---------+----------+          +---------+----------+
 | group   |  item    |          | group   |  item    |
 `````````````````````+          `````````````````````+
 |   A     |    1     |          |   s1    |    1     |
 |   A     |    2     |          |   s1    |    2     |
 |   A     |    5     |          |   s1    |    3     |
 |   B     |    4     |          |   s2    |    2     |
 |   B     |    5     |          |   s2    |    3     |
 |   C     |    3     |          |   s2    |    4     |
 |   C     |    5     |          |   s2    |    5     |
 +---------+----------+          +---------+----------+

Use this sqlfiddle to try: http://ift.tt/1b1mvOi

Or use the script below to generate temp tables to try out the answers:

create table #set1 (grp varchar(5),item int)
create table #set2 (grp varchar(5),item int)

insert into #set1 select 'a',1 union select 'a',2 union select 'a',5 union select 'b',4 union select 'b',5 union select 'c',3 union select 'c',5
insert into #set2 select 's1',1 union select 's1',2 union select 's1',3 union select 's2',2 union select 's2',3 union select 's2',4 union select 's2',5

select * from #set1
select * from #set2

--drop table #set1
--drop table #set2

How to use XML Auto to get the format obtained by XML Path in sql server

I am using sql server 2012.

This is my query:

CREATE TABLE #XmlTestTable 
(
    ID INT PRIMARY KEY IDENTITY(1,1),
    FirstName VARCHAR(20),
    LastName VARCHAR(20)
)
INSERT INTO #XmlTestTable (FirstName,LastName) VALUES
('John','Doe'),
('Jane','Doe'),
('Brian','Smith'),
('Your','Mom')

select  FirstName as "Name/@FN",LastName  as "Name/@LN" from #XmlTestTable for xml path('X'),root('Y')

It gives results like this:

<Y>
  <X>
    <Name FN="John" LN="Doe" />
  </X>
  <X>
    <Name FN="Jane" LN="Doe" />
  </X>
  <X>
    <Name FN="Brian" LN="Smith" />
  </X>
  <X>
    <Name FN="Your" LN="Mom" />
  </X>
</Y>

How can I obtain this format using XML AUTO

select  FirstName as "Name/@FN",LastName  as "Name/@LN" from #XmlTestTable for xml auto

generates this:

<_x0023_XmlTestTable Name_x002F__x0040_FN="John" Name_x002F__x0040_LN="Doe" />
<_x0023_XmlTestTable Name_x002F__x0040_FN="Jane" Name_x002F__x0040_LN="Doe" />
<_x0023_XmlTestTable Name_x002F__x0040_FN="Brian" Name_x002F__x0040_LN="Smith" />
<_x0023_XmlTestTable Name_x002F__x0040_FN="Your" Name_x002F__x0040_LN="Mom" />

And could anybody tell me why I get the sting like _x002F__x0040_FN in above format?

samedi 25 avril 2015

Find total number Employees going to get salary?

I have following Table Structure

    select row_number() over(order by [Group]) as [Rowid],[Group],
[per/person],[TotalPerson]
     from
    (select 'A' as [Group],3000 as [per/person],
5 as [TotalPerson] union All
    select 'B' ,2000 ,10  
union All
    select 'C' ,1000 ,15)A

declare @amt_avail int=24000

I need to find two result set:
1)How Many Employee will get the salary order by Row id?
Total Emp
9

2)How Many Maximum Employee get the salary ??
Max Emp
19

Query for matching IP address in SQL Server

I am trying to match IP addresses. The input IP address can be "5.1.82.1".

So, I am matching like first part of input IP address with all the IP address in database that start with 5. My query is like following

SELECT     top 1   PARSENAME(ipaddress, 4) AS firstpart, ipaddress
FROM            IPs
WHERE        (Country = 'pk') AND (PARSENAME(ipaddress, 4) <= '5')
ORDER BY Expr2 DESC

The above query results all the IP addresses that start with 5. Now I need to match the second part of the address which is "1" against the IP address range in the database. For that I will again do an "order by" and select the top record that is close to second part of the input IP address.

And so I will do the same for 3rd part and 4th part. But the question is how I can do it? I think I need to use a subquery. But where I will put it in my SQL statement.
UPDATE:
Sample data

from              to                  country
[5.1.82.0]       [5.1.82.255]         PK
[5.39.250.0]     [5.39.253.255]       PK
[5.39.255.0]     [5.39.255.255]       PK

IMPORTANT In database there are ranges of IP addresses for example: 5.1.82.0 to 5.1.82.255

INSERTing data with symbols

How should I go about inserting data in a database if there are symbol characters in the data to be inserted.

Sample Data inside a CSV File:

351442,351442,clc bed, futton 48" w/ mattres,9999.7500

351851,748485102207,CNTRY GRMT,BANGUS SPNSH184GX48,52.0000

352077,4806513109997,GLUTASILK, LOTION BLUE 50ML,57.5000

The data should be ITEM_NO,BARCODE,DESCRIPTION,PRICE

I have problems inserting the above data because of the Double Quotes and the Comma` inside the description.

First my program will take the line on the CSV File:

FileReader = New StreamReader(StringFileName)

Each line, I will split the data:TempArraySplitString = TempReaderString.Split(",")

Then insert the data:

        SqlCommand.CommandText = "INSERT INTO Items(Sku, Upc, Description, Price) VALUES('" & TempArraySplitString(0) & "','" & TempArraySplitString(1) & "','" & TempArraySplitString(2) & "','" & TempArraySplitString(3) & "')"
        SqlCommand.ExecuteNonQuery()

Error return since some line have , on the string.

How do I correctly separate each of the data to correctly insert into the database?

SQL management studio 2008 / local connect

i have installed windows 8.1(single language 64 bit) and have query about installed sql server managment studio 2008 64 bit...i am not able to connect my local sql server (PC NAME/SQLEXPRESS) .how can i solve that)

Write Sql Query

Build Sql Query We have a Sql Table Having Three Columns Viz Name_of_ffice , Month , Amount

Name_Of_Office---------------Month---------------------------- Amount------

DivisionBhopal--------------------04----------------------------------- 125--------------------------------- DivisionBhopal------------------- 05------------------------------------ 50-------------------------------------- DivisionBhopal------------------- 06----------------------------------- 100--------------------------------------------DivisionBhopal------------------- 10----------------------------------- 125-------------------------------------------- DivisionSagar-------------------- 04------------------------------------ 600------------------------------ DivisionSagar-------------------- 05------------------------------------ 520------------------------------- DivisionSagar-------------------- 06------------------------------------ 400--------------------------------------- DivisionSagar-------------------- 10------------------------------------ 100

Financial Year Month Should We Taken For Calculation . By the Formula Always Start sum From April to Selected Month Suppose User will Select Month June (from dropdown) Calculation Should be Performed Like this

Name_Of_Office----- Sum Upto Previous Month---- Present Month --------------Total Amount

DivisionBhopa------------- April + May--------------------------June-------------- --------April + May+ June-

DivisionSagar-------------- April + May ----------------------- June------------------------ April + May+ June

Here we will not add oct Amount because Selected Month is June we want data till june

For June Month Data Should look like------------------------------------------------------

Name_Of_Office---------Sum Upto Previous Month-----Present Month------------- Total Amount DivisionBhopal-------------------------- 175----------------------------- 100------------------------- 275 DivisionSagar--------------------------- 1120----------------------------- 400----------------------- 1520

For October Month Data Should look like (If User Select December)

Name_Of_Office-------- Sum Upto Previous Month----- Present Month-------------Total Amount DivisionBhopal------------------------- 275------------------------------- 125------------------------ 400 Divisionsagar-------------------------- 1520------------------------------- 100----------------------- 1620

Delete data records - keep joined data

I was not able to find a better title for this.

Branches          Users             Attendance
-----------------------------------------------
branchID^         userID^           courseID^
branchName        userName          userID*
                  branchID*

Here's my table. Due to company re-structure I need to delete old branches and the users that belong in them. But when my boss wants to see old Attendances he wants to see old userNames even if they don't exist.

What's the best practice here? I'm thinking to add a Disabled column in Branches/Users so they aren't visible on the web page.

Create Search For Site in VB.Net

i need to create a search engine for my site using 'vb.net' and i need to exactly like this site (a textbox in header and the result page).

my db is SQL server.

thanks.

Write a query to update the year in the date entry in the query table from 2012 to 2013.

also the following queries.

Accidentally the server date was set to a wrong value for 1 day. You have correctly set the date now. But you want to change all the date entries made on that day. Write a query to change the day by 1 of all dates in the query table on 31st Jan 2013.

Write a query to delete all queries from the query table posted before year 2012.

Write a query such that the experience table contains only the details regarding the past experience of the alumni.

The event 'ALUMNI MEET' has been postponed by 3 hours. Write a query to change the event time.

SQL select query from comma separated string

I have a table with with column location with values

row1: sector A, sector B, Sector c
row 2: sector B, sector f, Sector A
row 3: sector f

No I am looking for the sql query to search from these rows with comma separated string say I can search with Sector A, sector f in that case row 1 ,row2, row 3 values should print as Sector A is in row 1, row2 and sector f is in row 3

I am trying something like this but matches the exact string only ...

SELECT id , name FROM tb1 "+
" where    Charindex(','+cast(location  as     varchar(8000))+',',',"+loc+",') > 0

and loc is sector A,sector f

Foreign Key Constraints on an Intersection Table

I am trying to import data from an Excel document to MySQL Management Studio, and when attempting to do so, the data fails to import on a specific intersection table, which has the following data:

enter image description here

The table I am inserting to is called TYearLeagues, and the error I receive states that:

An OLE DB record is available. Source: "Microsoft SQL Server Native Client 11.0" Hresult: 0x80004005 Description: "The INSERT statement conflicted with the FOREIGN KEY constraint "TYearLeagues_TYears_FK". The conflict occurred in database "dbSQL2", table "dbo.TYears", column "intYearID"."

The intersection table is set up like so:

CREATE TABLE TYearLeagues
(
     intYearID              INTEGER         NOT NULL
    ,intLeagueID            INTEGER         NOT NULL
    ,CONSTRAINT TYearLeagues_PK PRIMARY KEY (intYearID, intLeagueID)
)

And the foreign key constraint like so:

ALTER TABLE TYearLeagues ADD CONSTRAINT TYearLeagues_TYears_FK
FOREIGN KEY ( intYearID ) REFERENCES TYears( intYearID )

Whereas I could understand an issue in a normal table, as TYearLeagues is an intersection table, and there are no duplicate records, I do not understand the issue.

"java.util.Scanner[delimiters=\p{javaWhitespace}+]" Error in JDBC program

I have written a jdbc application that has a function called "UpdateStudent," which takes the studentId as a parameter and then receives user input as to what the student's variables are to be changed to. The stored procedure works fine by itself within SQL server, but running things from java results in all string varaibles being changed to the value "java.util.Scanner[delimiters=\p{javaWhitespace}+]". However, my integer values are not affected, and are updated correctly. I believe the issue has to do with my implementation of the scanner in Java, since it works fine within SQL Server itself. Below is the function for UpdateStudent from my Main:

public static void updateStudent()
{
    System.out.print("\n Please enter the Id of a current student that you wish to update");
    System.out.print("\n==>");

    Student student = new Student();

    @SuppressWarnings("resource")

    Scanner insertstudentID = new Scanner(System.in);
    int passedStudentID = insertstudentID.nextInt(); //program starts counting at zero, but starts displaying at one

    System.out.print("\n Enter the new value for FirstName \n ==> ");
    @SuppressWarnings("resource")
    Scanner insertedFirstName = new Scanner(System.in);
    insertedFirstName.nextLine();        
    String passedFirstName = insertedFirstName.toString();
    student.setmFirstName(passedFirstName);

    System.out.print("\n Enter the new value for LastName \n ==> ");
    @SuppressWarnings("resource")
    Scanner insertedLastName = new Scanner(System.in);
    insertedLastName.nextLine();
    String passedLastName = insertedLastName.toString();
    student.setmLastName(passedLastName);

    System.out.print("\n Enter the new value for Num \n ==> ");
    @SuppressWarnings("resource")
    Scanner insertedNum = new Scanner(System.in);
    int passedNum = insertedNum.nextInt();
    student.setmNum(passedNum);

    student.updateStudent(passedStudentID, passedFirstName, passedLastName, passedNum);

    Scanner kb = new Scanner(System.in);
    System.out.print("\nHit Enter to continue...");
    String discard = kb.nextLine();           

}

Here is the function updateStudent from my Student class as well:

public void updateStudent(int studentId, String lastName, String firstName, int num) 
{

    Connection con = dbConnect();
    CallableStatement cs = null;
    ResultSet rs = null;
    //int studentId1=0;
    int returnVal=0;
    try {
        cs = con.prepareCall("{? = call updateStudent (?,?,?,?)}");
        cs.registerOutParameter(1, returnVal);
        cs.setInt(2, studentId);    //changed setint to registerOutParameter   
                                    //When changed setint to registerOutParameter   
                                    //error: The formal parameter "@studentId" was not declared 
                                    //as an OUTPUT parameter, but the actual parameter passed in requested output.
        cs.setString(3, firstName);            
        cs.setString(4, lastName);          
        cs.setInt(5,num);

        rs = cs.executeQuery();
       // cs.executeQuery();

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        if (rs != null) try { rs.close(); } catch(Exception e) {}
        if (cs != null) try { cs.close(); } catch(Exception e) {}
        if (con != null) try { con.close(); } catch(Exception e) {}
    }


}

I would appreciate any pointers about why I am getting this error. Everything seems to be compiling and running fine, so I think I might be just displaying my results incorrectly somehow.

Trying to implement an Ordered Job Queue in Sql Server 2012

I would like to implement an Ordered Job Queue in Sql Server 2012. Here is the context:

  1. Many agents concurrently taking N jobs from that queue, where N may be different for every agent (depends on the load of the particular agent).
  2. The jobs should be taken in order. Suppose it is the primary key order (in reality it is slightly different). So, agents should prefer older jobs.
  3. Some jobs have restricted concurrency. For example, if jobs A and B belong to the same concurrency group, then it is OK to queue both of them, but it is forbidden to run both of them at the same time. So, one of them runs first (according to the previously defined order) and only then can the second job be run.

Please, have a look at the following SQL Fiddle - http://ift.tt/1QuJ5jp

Ideally, I would use a single UPDATE TOP (N) statement with the READPAST hint and the OUTPUT clause. However, UPDATE does not promise any order, hence I utilize a different approach:

  1. An ordered SELECT TOP (N) into a temp table with the UPDLOCK and READPAST hints. In effect, I reserve these records.
  2. A regular UPDATE with the OUTPUT clause.

But then, such a bulk update may fail, because a job in the bulk is concurrency restricted. In this case I fall back to iterating over the reserved records and try to mark them as running one by one, silently skipping those that fail the concurrency restriction.

Here is the complete query from the SQL Fiddle:

BEGIN TRAN

exec sp_executesql N'
DECLARE @Running TABLE (WorkItemId BIGINT)

SELECT TOP (@Count) WorkItemId INTO #Candidates 
FROM BackgroundJobWork WITH (UPDLOCK, READPAST) 
WHERE Status = 0 
ORDER BY WorkItemId

BEGIN TRY
    PRINT '' *** BATCH *** ''
    UPDATE BackgroundJobWork SET Status = 3
    OUTPUT inserted.WorkItemId INTO @Running
    FROM BackgroundJobWork 
    WHERE WorkItemId IN (SELECT WorkItemId FROM #Candidates)
END TRY
BEGIN CATCH
    PRINT '' *** ONE BY ONE *** ''
    DECLARE @WorkItemId BIGINT
    DECLARE c CURSOR FAST_FORWARD FOR 
    SELECT WorkItemId FROM #Candidates ORDER BY WorkItemId

    OPEN c
    FETCH NEXT FROM c INTO @WorkItemId

    WHILE @@FETCH_STATUS = 0
    BEGIN
        BEGIN TRY
            UPDATE BackgroundJobWork SET Status = 3
            OUTPUT inserted.WorkItemId INTO @Running
            FROM BackgroundJobWork 
            WHERE WorkItemId = @WorkItemId
        END TRY
        BEGIN CATCH
        END CATCH

        FETCH NEXT FROM c INTO @WorkItemId
    END

    CLOSE c
    DEALLOCATE c
END CATCH

SELECT * FROM @Running
',N'@Count int',@Count=6

ROLLBACK

(Rolling back for the testing purposes, Status 0 means Received, Status 3 means Running)

So, there are two cases:

  1. No concurrency restriction - bulk updates do not fail
  2. There is a concurrency restriction - falling back to updating one by one with a cursor

My goal is to test that two agents running this query at the same time will not interfere with each other, i.e. none will be locked out waiting for the other to finish.

I simulate the presence of concurrency restrictions by running the following query first:

UPDATE BackgroundJobWork 
SET ConcurrencyGroupName = CONVERT(NVARCHAR(2), CASE 
  WHEN WorkItemId % 2 = 0 THEN NULL 
  ELSE WorkItemId % 4 
END) WHERE Status < 100

This yields the following result:

SELECT WorkItemId,Status,ConcurrencyGroupName FROM BackgroundJobWork 
WHERE Status < 100 ORDER BY WorkItemId

WorkItemId  Status  ConcurrencyGroupName
1           0       1
2           0       NULL
3           0       3
4           0       NULL
5           0       1
6           0       NULL
7           0       3
8           0       NULL
9           0       1
10          0       NULL
11          0       3
12          0       NULL

As you can see:

  • Jobs 1,5,9 belong to the concurrency restriction 1
  • Jobs 3,7,11 belong to the concurrency restriction 3
  • Jobs 2,4,6,8,10,12 are not concurrency restricted

UPDATE BackgroundJobWork SET ConcurrencyGroupName = NULL WHERE Status < 100 removes all the concurrency restrictions.

Unfortunately, I do not know how to demo two agents in the SQL Fiddle. Here is how I do it in my SSMS:

  1. Two SQL script windows, each one containing the query.
  2. In the first window comment out the ROLLBACK statement.
  3. Run the SQL from the first window. Note, that the transaction is still open, i.e. all the locks are still in place.
  4. Now run the SQL from the second window.
  5. At the end rollback the transaction from the first window by executing the ROLLBACK statement.

Bulk updates work great - the second window is not locked out by the open transaction started in the first window. I can see the jobs 1,2,3,4,5,6 in the first window and 7,8,9,10,11,12 - in the second.

However, when I simulate the concurrency restrictions (using the aforementioned query) the second window is locked and awaits for the first one to release the locks.

I am greatly puzzled by it. After all, each window updates only the records it has previously reserved with the respective SELECT statements! These sets are disjoint - UPDLOCK and READPAST guarantee it.

Appending - the locks held by the query

I am checking what locks are held (in yet another SSMS window) using the following query:

DECLARE @locks TABLE (spid INT,
                      dbid INT,
                      ObjId BIGINT,
                      IndId INT,
                      Type NVARCHAR(10),
                      Resource NVARCHAR(128),
                      Mode NVARCHAR(10),
                      Status NVARCHAR(32))
INSERT INTO @locks EXECUTE sp_lock

SELECT spid, OBJECT_NAME(ObjId) ObjectName, i.name, l.Type, Mode, COUNT(1) Count
FROM @locks l
LEFT JOIN sys.indexes i ON i.index_id = l.IndId AND i.object_id = l.ObjId
WHERE Mode NOT IN ('S','IS') AND dbid = DB_ID('747_DFControl2')
GROUP BY spid,OBJECT_NAME(ObjId),l.Type,i.name,Mode
ORDER BY spid,OBJECT_NAME(ObjId),l.Type,i.name,Mode

(747_DFControl2 is the name of my database)

If I run it when there are no concurrency restrictions (i.e. bulk updates are successful) I get the following output:

spid    ObjectName          name                    Type    Mode    Count
60      BackgroundJobWork   IX_Status               KEY     X       12
60      BackgroundJobWork   PK_BackgroundJobWork    KEY     X       6
60      BackgroundJobWork   IX_Status               PAG     IX      1
60      BackgroundJobWork   PK_BackgroundJobWork    PAG     IX      1
60      BackgroundJobWork   NULL                    TAB     IX      1

Where spid 60 corresponds to the first window (the one with the open transaction). We do not see the second window - it was successfully rolled back.

And here is the result when the concurrency restrictions are enabled and the second window (spid 63) is waiting for the release of the locks:

spid    ObjectName          name                        Type    Mode    Count
60      BackgroundJobWork   IX_ConcurrencyRestriction   KEY     X       2
60      BackgroundJobWork   IX_Status                   KEY     X       12
60      BackgroundJobWork   PK_BackgroundJobWork        KEY     X       6
60      BackgroundJobWork   IX_ConcurrencyRestriction   PAG     IX      1
60      BackgroundJobWork   IX_Status                   PAG     IX      1
60      BackgroundJobWork   PK_BackgroundJobWork        PAG     IX      1
60      BackgroundJobWork   NULL                        TAB     IX      1
63      BackgroundJobWork   IX_ConcurrencyRestriction   KEY     X       1
63      BackgroundJobWork   IX_Status                   KEY     X       12
63      BackgroundJobWork   PK_BackgroundJobWork        KEY     X       6
63      BackgroundJobWork   IX_ConcurrencyRestriction   PAG     IX      1
63      BackgroundJobWork   IX_Status                   PAG     IX      1
63      BackgroundJobWork   PK_BackgroundJobWork        PAG     IX      1
63      BackgroundJobWork   NULL                        TAB     IX      1

That does not tell me much.

Can someone explain to me why the second instance of the query is locked out?

EDIT

From the question it is unclear why would the bulk update fail when I turn on the concurrency restriction. It is clear, though, from the SQL Fiddle - there is a conditional unique index on the BackgroundJobWork table:

CREATE UNIQUE NONCLUSTERED INDEX IX_ConcurrencyRestriction ON BackgroundJobWork (ConcurrencyGroupName) 
WHERE (Status=3 AND ConcurrencyGroupName IS NOT NULL)

SQL SERVER 2008 - Returning a portion of text using SUBSTRING AND CHARINDEX. Need to return all text UNTIL a specific char

I have a column called 'response' that contains lots of data about a person.

I'd like to only return the info after a specific string

But, using the method below I sometimes (when people have <100 IQ) get the | that comes directly after the required number..

I'd like any characters after the'PersonIQ=' but only before the pipe.

I'm not sure of the best way to achieve this.

Query speed is a concern and my idea of nested CASE is likely not the best solution.

Any advice appreciated. Thanks

substring(response,(charindex('PersonIQ=',response)+9),3)

Updating database gives "The multi-part identifier could not be bound." Error

I'm trying to update the BookingID in the CounselorDB table. It's previously null. cID is a String that contains the predefined CounselorID.

The error I'm getting is the multi-part identifier "x" could not be bound; x being the cID.

Thank you.

 using (SqlConnection connection = new SqlConnection(connectionString))
    {
        String sql = string.Format("UPDATE CounselorDB SET BookingID = @BookingID WHERE CounselorID = " + cID);
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Connection = connection;
        cmd.Parameters.AddWithValue("@BookingID", getBookingID());
        connection.Open();
        cmd.ExecuteNonQuery();
    }

Import custom text format without separators

I would like import this .txt file format to SQL Server Table or to convert each block of text to pipe separated line.

Which tools or C# solution suggests you to resolve this issue?

Any suggestions would be appreciated.

Thank You.

=================
INPUT (.txt file)
=================
ID: 37
Name: Josephy Murphy
Email: jmurphy@email.com
Description: bla, bla, bla, bla...

ID: 38
Name: Paul Newman
Email: pnewman@email.com
Description: bla, bla, bla, bla...

:
:

=========================
OUTPUT (SQL Server Table)
=========================

ID | Name           | Email             | Description  
37 | Josephy Murphy | jmurphy@email.com | bla, bla, bla, bla...
38 | Paul Newman    | pnewman@email.com | bla, bla, bla, bla...

:
: 

php pdo sqlsrv not returning results?

i am trying to get results from mssql database table using php pdo , but its not returning any results , but i can count table rows , advice plz

  //this one working fine return 500 recrod in table
    $sql = "SELECT count(*) FROM Content";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $num_rows = $stmt->fetchColumn();

     //this one not returning anything 
    $sql = " SELECT c.*  FROM (
            SELECT ROW_NUMBER() OVER(ORDER BY ID) AS RowID,*  FROM Content
            ) AS c 
        WHERE c.ID > :row_start AND c.ID <= :row_end
        ";
       $stmt = $conn->prepare($sql);
       $stmt->bindParam(':row_start', $row_start);
       $stmt->bindParam(':row_end', $row_end);
       $stmt->execute();

    $allsuck = $stmt->fetchAll(PDO::FETCH_COLUMN);
     print_r($allsuck);

table info :

Array
(
    [0] => ID
    [1] => Title
    [2] => Fulldata
    [3] => description
    [4] => Catid
    [5] => language
    [6] => Created
    [7] => Userid
    [8] => MetaKey
    [9] => Thumbnail
    [10] => Thumbnail_desc
    [11] => Hits
    [12] => Active
    [13] => ModifiedDate
    [14] => ModifiedBy
    [15] => Fb_image
    [16] => important
    [17] => hashTags
)

SQL-Server: using an if in the where operator

I'm creating a stored procedure that gets values from a table that stores projects funding (their id, their goal and what they've received so far) And the proc would return either the project ID's that have been fully funded or those that haven't given a parameter @querytype; but I don't know how to put an if condition in a where; I've only ever used them in the select portion of a statement.

This is what I have so far but it just gives me "INCORRECT SYNTAX" on the first case...

--create proc Projects.GetFundedProjects -- Projects that have reached their goal
create proc Projects.GetFundedProjects
(@QueryType int
)
as
begin
select * from Stats.FundedProjectsToday
CASE 
WHEN @QueryType = 1 -- Projects that reached their goal
THEN
     where AUReceived=>ProjectGoal
WHEN @QueryType = 2 -- Projects that have not been funded
THEN 
    where AUReceived<ProjectGoal
end --end the case
end -- end the proc

SQL Query Looking for optimisation for complex query with indexes

$query = "SELECT * 
          FROM $database1 
          WHERE userid!='$userid' 
            AND mediaid NOT IN (SELECT mediaid 
                                FROM $database2 
                                WHERE uid='$userid')
          ORDER BY active ASC LIMIT 80";

This query was working very well until now.

That it suddenly takes 0.5 to sometimes even 3s to execute, sometimes it also goes down to 0.1 which is acceptable.

Now database2 has around 3 millionn rows and database1 around 500, but it also sometimes is slow when only 100 items in database1. I'm worried because database2 is getting around 30k new rows each day.

Both mediaid, userid, uid are all indexes.

Server? 8cores x 3,2, 16gb ram. Scalable cloud. Average load is fine. not more than 20% cpus

How to add a single quote when I have single quote in PHP for SQL Management studio

I am having trouble with SQL Management studio and I do not want to connect to this SQL server I want to make the data ready for my lines to be inserted in this database I have a text file with the lines of strings that I want to insert in sql server the line is like this:

You're Doing It Wrong!!,Mike Walsh,Intermediate

So it should be like this to be ready for sql server.

You''re Doing It Wrong!!,Mike Walsh,Intermediate

I also have this in lines:

Never Have to Say "Mayday!!!" Again

Is this one going to become a problem? Should I have any plan for it also?

I tried to use addslash and then replace the slash with the a single quote by doing:

  $str=",('".addslashes ($array[0])."')";
     $str=str_replace("\\","\'",$str);
     echo $str;

I did the comma and parenthesis for when I have insert to query in sql server the result of this one will be:

    ,('You\''re Doing It Wrong!!'),
,('Never Have to Say \'"Mayday!!!\'" Again'),

What did I do wrong here?

"Cannot resolve collation conflict" even after fixing the collation

The current database I'm using "PrimaryDatabase" has the collation "SQL_Latin1_General_CP1_CI_AS", while the "SecondaryDatabase" I'm trying to access has the collation "Arabic_CI_AS"

I changed the collation for the SecondaryDatabase and set it to " SQL_Latin1_General_CP1_CI_AS" and made sure it has been changed as well as in its tables.

However, when i run the query below I still get collation conflict.

select * from [MYSERVER].[SecondaryDatabase].[dbo].[SecondaryTableName] 
where ltrim(rtrim([SecondaryTablename])) not in (select ltrim(rtrim(PrimaryFieldname))  from PrimaryTablename where PrimaryFieldName2=1)

how i can access local web or database server remotely without static IP

how i can access my local web server or database server access remotely without static ip address, i have desktop database driven app which is saving data in MS SQL server i want to access data on company current site hosted on bluehost, is there any way to access following points

  1. MS SQL server remote acces without static IP address
  2. Or I will write a web service in PHP connected with MS SQL database sending REST API information to online site how to access local web server without static ip address

update sql in asp.net

what's the error on this when i run it it's give me this error ""String or binary data would be truncated. The statement has been terminated."" it's update by using ID that i take it from Drop Down list

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string constr = "Data Source=YAZAN-PC ; initial Catalog=Elder ; user = sa ; pwd =yazan7;";
        SqlConnection con = new SqlConnection(constr);
        string sql = "Select * from Users;";
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        con.Close();
        DataRow dr = dt.NewRow();
        dr["ID"] = "0";

        dt.Rows.InsertAt(dr, 0);
        ddlID.DataSource = dt;

        ddlID.DataValueField = "ID";
        ddlID.DataBind();
    }
}

protected void btnUpdate_Click(object sender, EventArgs e)
{
    string constr = "Data Source = YAZAN-PC ;" +
                   "initial catalog = Elder;" +
                   "user = sa ; pwd = yazan7;";
    SqlConnection con = new SqlConnection(constr);
    string Sql =
    "Update Users Set Name=@Name , Gender=@Gender , Email=@Email ,UserType=@UserType, BirthDate=@BirthDate , Password=@Password, RePassword=@RePassword where ID=@ID;";
   con.Open();
    SqlCommand cmd = new SqlCommand(Sql, con);

    cmd.Parameters.AddWithValue("@Name", txtName.Text);
    cmd.Parameters.AddWithValue("@Gender", rblGender.SelectedValue);
    cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
    cmd.Parameters.AddWithValue("@UserType", rblUserType.SelectedValue);
    cmd.Parameters.AddWithValue("@BirthDate", txtBirthDate.Text);
    cmd.Parameters.AddWithValue("@Password", txtPassword.Text);
    cmd.Parameters.AddWithValue("@RePassword", txtRePassword.Text);
    cmd.ExecuteNonQuery();
    con.Close();
}

Inserting N child entities makes N queries. Bulk insert for child entities?

I know I can insert multiple entities using AddRange() and it will only make one trip to the database. In my case I'm inserting a single entity which has, for instance, 15 child entities. In this case Mini Profiler says I'm doing 15 duplicate queries, which afaik means that it takes 15 database trips no insert the child entities.

Question is - how can I bulk insert N child entities in one go? The amount of data in entities is incredibly small (few lines of text).

Split into different columns SQL Server

I've got data in a column of my table just like this:

cpc > cpc > organic
cpc > organic >cpc
mail > cpc > organic

How can I split that data to different columns using '>' as a delimiter?

Change SQL Server primary key using C#

I need to change a column type in a SQL Server table.

I need do it using a script or C#.

The original datatype is integer and the new type is varchar(50).

I can do it using this SQL script:

ALTER TABLE confezionamento ALTER COLUMN partnumber varchar(50) 

but the problem is that this column is in a set of primary keys.

When I try do execute, an error occurred because PK_CONFEZIONAMENTO is using the column.

How I can do it without access to SQL Server Management Studio?

SQL Compare rows

Okay here is the situation: I the following data in a table.

PAIR_NO NO          NO2

3       5678EFGH    1234ABCD
4       1111BBBB    0000AAAA
1       1234ABCD    5678EFGH
2       0000AAAA    1111BBBB

The constraints are if no = no2 in another row skip that row. So in this sample data the only rows that would be selected should be pair no 3 and 4.

I have tried to merge and inner join with self but I just keep getting all 4 rows back.

I have tried to insert into a table where not exists but again I get 4 rows inserted.

   SELECT a.* from PAIRS a
   inner join PAIRS b on a.no=b.no2 and a.no2=b.no;

I was thinking maybe selecting distinct number from column 1 and then check those in column 2 but I think that would yield the same four rows.

I may be over thinking this problem and maybe some here can look at this and see where the solution is hiding.

I am currently testing this on MySQL but it should run on SQLServer 2008. I have searched but all the questions didn't seem to match my data set issue.

adding unique constraint on database column

If I already have primary key on column Id and I have column Name on which I want to add Unique constraint how can I do that in mssql?

What is the name of a table that joins two other tables?

What is the name for a database entity that joins two other entities using composite keys? I'm asking as I'm writing a theoretical definition for my studies.

SQL Azure Standard Geo replication - Promote Non readable secondary replica to Primary

For Disaster recovery scenario , I have created a Primary DB and using standard Geo replication , created a secondary replica.

I wanted to simulate the DR / DR Drill so I have used the below powershell CMDLET for terminating the the continuous copy relationship and to promote the secondary replica to primary.

Stop-AzureSqlDatabaseCopy -ServerName "S1"-DatabaseName "ActiveGeoReplicationDemo"-PartnerServer "S2"

This works fine for Active geo-replication, but throwing error for the Standard geo-replication as below,

Stop-AzureSqlDatabaseCopy : Friendly termination of an offline secondary relationship is not supported.

I thought the deletion of primary db would promote the secondary to primary automatically and deleted the primary. As expected, with active Geo-replication , the secondary has been promoted to the primary But in the Standard GEO-Rep still the seconday is Nonreadable and in the offline status.

So the Question is , How can i promote the non-readable Secondary DB to primary using Standard geo-replication? ( How Fail-over and fail-back to be done?)

It would be great if i get the powershell cmdlets or some references for this.

How could i connect to SQL Server from my Xcode 5 application

For an ERP application in ios I have to connect sql server. And i done using json parsing. But i do not know how get and post data from xcode 5 to sql server.

Azure SQL Database Clearing or Reseting?

I have created a basic .NET C# web application with role, user and group authentication. The code is almost entirely pulled from this tutorial here:

http://ift.tt/1IWmWFk

This code appears to be working by many people in the online community, however something is going wrong and I'm trying to figure out what that is.

I have run through the code several times and can't seem to find an error. I am storing the connection to my Azure SQL Database in the Web.config file in the app, and it seems to be working. I am able to create, edit and delete users, roles and groups and see those changes in the database, but after an hour when I revisit the app it is like the SQL Database has restored itself to a previous version and reset, or dumped all my data. Everything is gone.

Has anyone else ran into a similar issue with the free Azure account?

How to convert or rewrite Access IIF Statement in SQL Server

I thought the IIf statements returns one value if the condtion is true or false BUT This IIf statement in Access returns the field and it values.

IIf([A1]![KPr],[A1]![Kat],IIf([Data2]![Kat],[Data2]![Kat],[Data1]![Kat])),

the table left join in the from clause I'm try to realize this statement in 'SQL Server' using 'CASE WHEN' but it also accepts a true or false condition.

How can I understand and realize this statement.

Getting print messages from sqlserver to java application

I have a stored procedure which prints a simple string:

create proc proc1  
as  
print 'Hello World !'

I have an android application which uses servlet (written in Java) for making connection to SQL server Data base. The next code is inside the servlet:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 = DriverManager.getConnection("Jdbc:Odbc:abc");
CallableStatement cstmt=con1.prepareCall("{call proc1}");
cstmt.execute();

It works fine. The procedure is being activated but now, I want to get the print message 'Hello world !' but the following code doesn't work, and SQLWarning always gets null:

SQLWarning warning = cstmt.getWarnings();
while (warning != null)
{
   System.out.println(warning.getMessage());
   warning = warning.getNextWarning();
}    

My question is how can I get thess print messages? P.S Using raiserror instead of print didn't work as well. I know already about the option of output parameters (I investigated this subject for almost a week). With your permission I would like to ask for another option.

Prevent a value from being entered if it's a prefix of another value

How could I prevent a value from being entered that is a prefix of another value in the same column? For example, if MyTable.NumberPrefix already contains abc then ab can't be added.

My first attempt (below) was to use an indexed view. But a unique index cannot be created on a view that uses a derived table (and I can't figure out how to write the view without it).

create view MyTable
with schemabinding
as
select
  left(a.NumberPrefix, b.Length) as CommonPrefix
from 
  dbo.MyTable a
  cross join
  (
    select distinct
      len(NumberPrefix) as Length
    from
      dbo.MyTable
  ) b

create unique clustered index MyIndex on MyTable (CommonPrefix) --ERROR

connecting to the SQLServer database with C#

i find out a connection string to create wizardless connection to the SQLServer database, but i don`t know something about it, the question is where can i find SQL version for example SQLEXPRESS and where is application.StartupPath in Visual studio folders, so i can copy my database to that path, any better method will be appreciated, below the string connection is presented :

" Data Source = .\SQLEXPRESS;AttachDbFilename=\""+Application.StartupPath+"\my_database_name.mdf\";Integrated Security = True; Connect Timeout=30;User Instance = True";

making MULTIPLE subgroup aggregations

I’m trying to create sub-records with aggregations mined from existing records in our data. I have a table that lists records, with a one to many relationship to another that lists actions on each record. Record table looks like this:

Key  OpenDate  LastUpdate
aa   1/1/2015  1/14/2015
bb   1/3/2015  1/15/2015

Action table looks like this:

    Key  Date     Action
    aa  1/1/2015    Working
    aa  1/4/2015    Escalated
    aa  1/5/2015    Done
    aa  1/6/2015    Working
    aa  1/7/2015    Done
    aa  1/13/2015   Done
    aa  1/14/2015   Working
    bb  1/3/2015    Working
    bb  1/4/2015    Working
    bb  1/5/2015    Escalated
    bb  1/6/2015    Working
    bb  1/7/2015    Done
    bb  1/13/2015   Working
    bb  1/15/2015   Done  

I want to be able to create a row for each time a record gets 'done' that notes the start and end of that cycle, and counts some items within that range:

Key  SubID  DateBegin   DateEnd   #Actions #Escalations
aa   1     1/1/2015    1/5/2015    3       1
aa   2     1/6/2015    1/7/2015    2       0
aa   3     1/13/2015   1/13/2015   1       0
aa   4     1/14/2015   null        1       0
bb   1     1/3/2015    1/7/2015    5       1
bb   2     1/13/2015   1/15/2015   2       0

Basically, the logic is that a sub-record ends when the Action value = ‘Done’, and a new sub-record begins on any subsequent action (and also the very first action).

I was shown a solution that works for only one record's data here , but more than one is giving me problems. I am working with SQL Server 2008.

UPDATE -- I've got multiple records returning but the date data seems incorrect - not sure it's getting what it is supposed to:

SELECT Key, Cycles.CYCLE_BEGIN_DATE, Cycles.CYCLE_END_DATE, Cycles.NUM_ACTIONS_IN_CYCLE
FROM Records
FULL OUTER JOIN
    (select e.Key, min(Date) as CYCLE_BEGIN_DATE,
          max(case when Action = 'Done') then Date end) as CYCLE_END_DATE,
          count(*) as NUM_ACTIONS_IN_CYCLE
    from (select Key, Action, rowID = ROW_NUMBER() OVER (PARTITION BY Key ORDER BY Date asc), Date
     from Actions
   ) e
   outer apply
    (select count(*) as grp
        from (SELECT Key, rowID = ROW_NUMBER() OVER (PARTITION BY Reason_Key ORDER BY Date asc), Date, Action
    FROM Actions
   ) e2
   where e2.Date < e.Date and e2.Action = 'Done' and e.Reason_Key = e2.Reason_Key
   ) e2
   group by e.Reason_Key, e2.grp
) CYCLES
on Records.Key = Cycles.Key

Using a SQL function to pad strings with spaces

Is it inefficient to use a user defined function to pad spaces? I have a padding function that I'd more intuitive than using the built in REPLICATE function but I am afraid it is introducing inefficiency into the code.

The padding must be done in SQL.

SQL ID from table posts same ID to all other coldfusion entries per transaction

How do I trigger my ID from my Transaction table to be the same on all entries to each table per session? I am trying to insert a lot of information to many tables but trying to keep all tables linked together by TransactionID and am struggling on how it creates the TransactionID with the first entry then grabbing that entry and using it on all other table entries.

(This is my insert to create the Transaction. This should automatically create an ID in my Transaction table since ID is my primary key in the transaction table and IsIdentity is yes and increment of one)

<cfquery datasource="Titlesbymail" name="InsertEntry">
 INSERT INTO dbo.Transaction (Type, OwnerType)
 VALUES (
    <cfqueryparam value='NonLeased' cfsqltype='cf_sql_varchar' />
   , <cfqueryparam value='Owner' cfsqltype='cf_sql_varchar' />
 )
</cfquery>

This then creates the transaction table:
ID: 1
Type: NonLeased
OwnerType: Owner

I am trying to figure out how I can keep that same transaction ID to be inserted with my next entries to my other 6 Tables (if the table exists)

<cfquery datasource="Titlesbymail" name="CustomerInsertEntry">
 INSERT INTO dbo.Customer (TransactionID, ID, FirstName, LastName)
 VALUES (
    <cfqueryparam value= **'(ID from Transaction Table)'** cfsqltype='cf_sql_int' />
   , <cfqueryparam value='1' cfsqltype='cf_sql_int' />
   , <cfqueryparam value='#session.checkout.info.firstname_1#' cfsqltype='cf_sql_varchar' />
   , <cfqueryparam value='#session.checkout.info.lastname_1#' cfsqltype='cf_sql_varchar' />
 )
</cfquery>

This is completely new to me and have done lots of research I just keep coming across sql commands of triggers and all but have no idea how that applies with my coldfusion set up like this.

How do I get the textbox value to the database within a repeater?

I have a repeater that I populate from a database:

using (SqlConnection conn = new SqlConnection(connString))
{
   SqlCommand cmd = new SqlCommand(@"SELECT CommunityName, CID, Budget FROM Donation WHERE Year = year(getdate()) ORDER BY CommunityName", conn);
   conn.Open();
   SqlDataAdapter adp = new SqlDataAdapter(cmd);
   DataSet myDataSet = new DataSet();
   adp.Fill(myDataSet);
   myRep.ItemDataBound += new RepeaterItemEventHandler(myRep_ItemDataBound);
   myRep.DataSource = myDataSet;
   myRep.DataBind();
}
void myRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   var textbox = e.Item.FindControl("community");
   textbox.ClientIDMode = ClientIDMode.Static;
   textbox.ID = "community" + (e.Item.ItemIndex + 1);
 }

Repeater:

<asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Always">
    <ContentTemplate>
       <asp:Repeater ID="myRep" runat="server">
          <ItemTemplate>
             <div class="form-group">
                <asp:Label ID='thisLbl' runat="server" Text='<%# Eval("CommunityName") %>' />
                <asp:TextBox runat="server" ID="community" Text='<%# Eval("Budget") %>' CssClass="form-control" />
             </div>
          </ItemTemplate>
       </asp:Repeater>
    </ContentTemplate>
</asp:UpdatePanel>

This creates 6 textboxes with labels and values, now my question is how do I detect which of these boxes belongs to the record it was initially pulled from in the database? I want to be able to modify the value in these boxes and hit a button to save them back to the database but I can't seem to wrap my head around getting them to the proper records.

Should I set the ID of the textbox to something I can parse through and match with the proper record? In the ItemDataBound?

log4net to sql c# example

I don't know why its so hard to find a simple example but can someone point me to sample c# code w/ sample sql appender code that allows me to save data to a sql database table that takes in a couple simple parameter like a UserID & UserName.

Thanks & that's it.

I found many examples of the DB appender but none w/ the c# code to execute the logging.

Please don't flag this & say it was asked & already point me to a solution that EXCLUDES the the c# code. I'd can use log4net to log to a file but am lost writing the c# code to leverage the appender for a simple table I set up.

Thanks!

Connect to SQL Server from ASP.NET MVC application

I am entirely new to ASP.NET MVC. I have one ASP.NET 2.0 Framework Web application with below architecture

  • Web Based Application 3 - Tier Architecture
  • Data Access Layer C#, ADO.NET
  • Database – SQL Server 2008 R2
  • Authentication - Forms

I am moving the application to an ASP.NET MVC 4 architecture; can anybody suggest the best practices to go with for data access layer, assume the connection string will be in web.config?

Code-first? Or data-first approach? What is the difference with the above approach and Entity Framework?

Also while adding a controller for a model, amongst the below template which I need to choose?

  1. Empty ASP.NET MVC controller
  2. ASP.NET MVC controller with read/write actions using Entity Framework
  3. ASP.NET MVC controller with empty read/write actions
  4. Empty API controller
  5. API controller with read/write actions using Entity Framework
  6. API controller with empty read/write actions

What is the difference between the above templates?