Search Results

Search found 1805 results on 73 pages for 'varchar'.

Page 7/73 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • How to switch from VARCHAR to TEXT in SQL 2000?

    - by MatthewMartin
    What do I need to consider before I switch a bunch of fields from VARCHAR(bignumber) to TEXT? Aside from performance, and sometime in the far future TEXT will be deprecated, and aside from the fact that it looks like I need to drop and recreate the table to alter the column's data type? This is for SQL 2000-- I can't do VARCHAR(max) and VARCHAR(8000) isn't large enough.

    Read the article

  • How to generate a script for changing a column of varchar to xml type with data being converted?

    - by user1323981
    Initially I have a column (partner_email) of varchar.Now a recent change has come where it needs to be changed to be changed to the XML type but the previous records needs to be reserve into the new column. I have applied the below algorithm to accomplish the work /*********************************************************************** Purpose: To change the partner_email column from Varchar Type To Xml Type and convert the existing records from varchar to xml types. Programmers Notes: 1. Create a new Column by the name partner_email_temp of type XML into the Partner Table 2. Copy the Email contents from partner_email to partner_email_temp column after proper conversion N.B.~ The format will be <PartnerEmails> <Email>[email protected]</Email> <Email /> <Email /> </PartnerEmails> 3. Drop the exisitng partner_email 4. Rename partner_email_temp column to partner_email ***********************************************************************/ USE [Test] GO --===== Create a partner_email_temp column of type xml into the Partner table IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.columns WHERE table_name = 'Partner' AND column_name = 'partner_email_temp' ) BEGIN ALTER TABLE [dbo].[Partner] ADD partner_email_temp XML NULL END GO --===== Copy the Email contents from partner_email to partner_email_temp column -- after proper conversion to xml type UPDATE [dbo].[Partner] SET partner_email_temp = CAST('<PartnerEmails><Email>' + REPLACE(partner_email, '&', '&amp;') + '</Email><Email></Email><Email></Email></PartnerEmails>' AS XML) GO --===== Drop the exisitng partner_email ALTER TABLE [dbo].[Partner] DROP COLUMN partner_email GO --===== Rename partner_email_temp column to partner_email Exec sp_RENAME 'Partner.partner_email_temp','partner_email','COLUMN' GO I works fine for the first time I ran. Now if I ran it for the next time, it am getting an error Msg 8116, Level 16, State 1, Line 4 Argument data type xml is invalid for argument 1 of replace function. Caution: Changing any part of an object name could break scripts and stored procedures. The intention is that, if the partner_email column is varchar, the script will change it to xml type and will convert all the data in xml format . If I ran it second time, it should ignore the statement. How to achieve this? I am trying in a different way DECLARE @columnDataType VARCHAR(50) SELECT @columnDataType = DATA_TYPE FROM INFORMATION_SCHEMA.columns WHERE table_name = 'Partner' AND column_name = 'partner_email' print @columnDataType IF (@columnDataType = 'varchar') BEGIN --===== Create a partner_email_temp column of type xml into the Partner table IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.columns WHERE table_name = 'Partner' AND column_name = 'partner_email_temp' ) BEGIN ALTER TABLE [dbo].[Partner] ADD partner_email_temp XML NULL --===== Copy the Email contents from partner_email to partner_email_temp column -- after proper conversion to xml type UPDATE [dbo].[Partner] SET partner_email_temp = CAST('<PartnerEmails><Email>' + REPLACE(partner_email, '&', '&amp;') + '</Email><Email></Email><Email></Email></PartnerEmails>' AS XML) --===== Drop the exisitng partner_email ALTER TABLE [dbo].[Partner] DROP COLUMN partner_email --===== Rename partner_email_temp column to partner_email EXEC sp_RENAME 'Partner.partner_email_temp','partner_email','COLUMN' END END but getting error Msg 207, Level 16, State 1, Line 29 Invalid column name 'partner_email_temp'. Help needed

    Read the article

  • Trying to import SQL file in a xampp server returns error

    - by Victor_J_Martin
    I have done a ER diagram in Mysql Workbench, and I am trying load in my server with phpMyAdmin, but it returns me the next error: Error SQL Query: -- ----------------------------------------------------- -- Table `BDA`.`UG` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `BDA`.`UG` ( `numero_ug` INT NOT NULL, `nombre` VARCHAR(45) NOT NULL, `segunda_firma_autorizada` VARCHAR(45) NOT NULL, `fecha_creacion` DATE NOT NULL, `nombre_depto` VARCHAR(140) NOT NULL, `dni` INT NOT NULL, `anho_contable` INT NOT NULL, PRIMARY KEY (`numero_ug`), INDEX `nombre_depto_idx` (`nombre_depto` ASC), INDEX `dni_idx` (`dni` ASC), INDEX `anho_contable_idx` (`anho_contable` ASC), CONSTRAINT `nombre_depto` FOREIGN KEY (`nombre_depto`) REFERENCES `BDA`.`Departamento` (`nombre_depto`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `dni` FOREIGN KEY (`dni`) REFERENCES `BDA`.`Trabajador` (`dni`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `anho_contable` FOREIGN KEY (`anho_contable`) REFERENCES `BDA`.`Capitulo_Contable` (`anho_contable`) [...] MySQL said: Documentation #1022 - Can't write; duplicate key in table 'ug' I export the result of the diagram from Mysql Workbench to a SQL file, and this file is what I'm trying to upload. This is the file. I can not find the duplicate key. SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; CREATE SCHEMA IF NOT EXISTS `BDA` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ; USE `BDA` ; -- ----------------------------------------------------- -- Table `BDA`.`Departamento` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `BDA`.`Departamento` ( `nombre_depto` VARCHAR(140) NOT NULL, `area_depto` VARCHAR(140) NOT NULL, PRIMARY KEY (`nombre_depto`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `BDA`.`Trabajador` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `BDA`.`Trabajador` ( `dni` INT NOT NULL, `direccion` VARCHAR(140) NOT NULL, `nombre` VARCHAR(45) NOT NULL, `apellidos` VARCHAR(140) NOT NULL, `fecha_nacimiento` DATE NOT NULL, `fecha_contrato` DATE NOT NULL, `titulacion` VARCHAR(140) NULL, `nombre_depto` VARCHAR(45) NOT NULL, PRIMARY KEY (`dni`), INDEX `nombre_depto_idx` (`nombre_depto` ASC), CONSTRAINT `nombre_depto` FOREIGN KEY (`nombre_depto`) REFERENCES `BDA`.`Departamento` (`nombre_depto`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `BDA`.`Capitulo_Contable` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `BDA`.`Capitulo_Contable` ( `anho_contable` INT NOT NULL, `numero_ug` INT NOT NULL, `debe` DOUBLE NOT NULL, `haber` DOUBLE NOT NULL, PRIMARY KEY (`anho_contable`), INDEX `numero_ug_idx` (`numero_ug` ASC), CONSTRAINT `numero_ug` FOREIGN KEY (`numero_ug`) REFERENCES `BDA`.`UG` (`numero_ug`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `BDA`.`UG` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `BDA`.`UG` ( `numero_ug` INT NOT NULL, `nombre` VARCHAR(45) NOT NULL, `segunda_firma_autorizada` VARCHAR(45) NOT NULL, `fecha_creacion` DATE NOT NULL, `nombre_depto` VARCHAR(140) NOT NULL, `dni` INT NOT NULL, `anho_contable` INT NOT NULL, PRIMARY KEY (`numero_ug`), INDEX `nombre_depto_idx` (`nombre_depto` ASC), INDEX `dni_idx` (`dni` ASC), INDEX `anho_contable_idx` (`anho_contable` ASC), CONSTRAINT `nombre_depto` FOREIGN KEY (`nombre_depto`) REFERENCES `BDA`.`Departamento` (`nombre_depto`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `dni` FOREIGN KEY (`dni`) REFERENCES `BDA`.`Trabajador` (`dni`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `anho_contable` FOREIGN KEY (`anho_contable`) REFERENCES `BDA`.`Capitulo_Contable` (`anho_contable`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `BDA`.`Cliente` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `BDA`.`Cliente` ( `cif_cliente` INT NOT NULL, `nombre_cliente` VARCHAR(140) NOT NULL, PRIMARY KEY (`cif_cliente`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `BDA`.`Ingreso` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `BDA`.`Ingreso` ( `id` INT NOT NULL, `concepto` VARCHAR(45) NOT NULL, `importe` DOUBLE NOT NULL, `fecha` DATE NOT NULL, `cif_cliente` INT NOT NULL, `numero_ug` INT NOT NULL, PRIMARY KEY (`id`), INDEX `cif_cliente_idx` (`cif_cliente` ASC), INDEX `numero_ug_idx` (`numero_ug` ASC), CONSTRAINT `cif_cliente` FOREIGN KEY (`cif_cliente`) REFERENCES `BDA`.`Cliente` (`cif_cliente`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `numero_ug` FOREIGN KEY (`numero_ug`) REFERENCES `BDA`.`UG` (`numero_ug`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `BDA`.`Proveedor` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `BDA`.`Proveedor` ( `cif_proveedor` INT NOT NULL, `nombre_proveedor` VARCHAR(140) NOT NULL, PRIMARY KEY (`cif_proveedor`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `BDA`.`Gasto` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `BDA`.`Gasto` ( `id` INT NOT NULL, `concepto` VARCHAR(45) NOT NULL, `importe` DOUBLE NOT NULL, `fecha` DATE NOT NULL, `factura` INT NOT NULL, `cif_proveedor` INT NOT NULL, `numero_ug` INT NOT NULL, PRIMARY KEY (`id`), INDEX `cif_proveedor_idx` (`cif_proveedor` ASC), INDEX `numero_ug_idx` (`numero_ug` ASC), CONSTRAINT `cif_proveedor` FOREIGN KEY (`cif_proveedor`) REFERENCES `BDA`.`Proveedor` (`cif_proveedor`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `numero_ug` FOREIGN KEY (`numero_ug`) REFERENCES `BDA`.`UG` (`numero_ug`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; Thanks for your advices.

    Read the article

  • DBD::SQLite::st execute failed: datatype mismatch

    - by Barton Chittenden
    Here's a snippit of perl code: sub insert_timesheet { my $dbh = shift; my $entryref = shift; my $insertme = join(',', @_); my $values_template = '?, ' x scalar(@_); chop $values_template; chop $values_template; #remove trailing comma my $insert = "INSERT INTO timesheet( $insertme ) VALUES ( $values_template );"; my $sth = $dbh->prepare($insert); debug("$insert"); my @values; foreach my $entry (@_){ push @values, $$entryref{$entry} } debug("@values"); my $rv = $sth->execute( @values ) or die $dbh->errstr; debug("sql return value: $rv"); $dbh->disconnect; } The value of $insert: [INSERT INTO timesheet( idx,Start_Time,End_Time,Project,Ticket_Number,Site,Duration,Notes ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ? );] Here are @values: [null '1270950742' '1270951642' 'asdf' 'asdf' 'adsf' 15 ''] Here's the schema of 'timesheet' timesheet( idx INTEGER PRIMARY KEY AUTOINCREMENT, Start_Time VARCHAR, End_Time VARCHAR, Duration INTEGER, Project VARCHAR, Ticket_Number VARCHAR, Site VARCHAR, Notes VARCHAR) Here's how things line up: ---- Insert Statement Schema @values ---- idx idx INTEGER PRIMARY KEY AUTOINCREMENT null: # this is not a mismatch, passing null will allow auto-increment. Start_Time Start_Time VARCHAR '1270950742' End_Time End_Time VARCHAR '1270951642' Project Project VARCHAR 'asdf' Ticket_Number Ticket_Number VARCHAR 'asdf' Site Site VARCHAR 'adsf' Duration Duration INTEGER 15 Notes Notes VARCHAR '' ... I can't see the data-type mis-match.

    Read the article

  • How to speed up this simple mysql query?

    - by Jim Thio
    The query is simple: SELECT TB.ID, TB.Latitude, TB.Longitude, 111151.29341326*SQRT(pow(-6.185-TB.Latitude,2)+pow(106.773-TB.Longitude,2)*cos(-6.185*0.017453292519943)*cos(TB.Latitude*0.017453292519943)) AS Distance FROM `tablebusiness` AS TB WHERE -6.2767668133836 < TB.Latitude AND TB.Latitude < -6.0932331866164 AND FoursquarePeopleCount >5 AND 106.68123318662 < TB.Longitude AND TB.Longitude <106.86476681338 ORDER BY Distance See, we just look at all business within a rectangle. 1.6 million rows. Within that small rectangle there are only 67,565 businesses. The structure of the table is 1 ID varchar(250) utf8_unicode_ci No None Change Change Drop Drop More Show more actions 2 Email varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 3 InBuildingAddress varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 4 Price int(10) Yes NULL Change Change Drop Drop More Show more actions 5 Street varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 6 Title varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 7 Website varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 8 Zip varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 9 Rating Star double Yes NULL Change Change Drop Drop More Show more actions 10 Rating Weight double Yes NULL Change Change Drop Drop More Show more actions 11 Latitude double Yes NULL Change Change Drop Drop More Show more actions 12 Longitude double Yes NULL Change Change Drop Drop More Show more actions 13 Building varchar(200) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 14 City varchar(100) utf8_unicode_ci No None Change Change Drop Drop More Show more actions 15 OpeningHour varchar(400) utf8_unicode_ci Yes NULL Change Change Drop Drop More Show more actions 16 TimeStamp timestamp on update CURRENT_TIMESTAMP No CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP Change Change Drop Drop More Show more actions 17 CountViews int(11) Yes NULL Change Change Drop Drop More Show more actions The indexes are: Edit Edit Drop Drop PRIMARY BTREE Yes No ID 1965990 A Edit Edit Drop Drop City BTREE No No City 131066 A Edit Edit Drop Drop Building BTREE No No Building 21 A YES Edit Edit Drop Drop OpeningHour BTREE No No OpeningHour (255) 21 A YES Edit Edit Drop Drop Email BTREE No No Email (255) 21 A YES Edit Edit Drop Drop InBuildingAddress BTREE No No InBuildingAddress (255) 21 A YES Edit Edit Drop Drop Price BTREE No No Price 21 A YES Edit Edit Drop Drop Street BTREE No No Street (255) 982995 A YES Edit Edit Drop Drop Title BTREE No No Title (255) 1965990 A YES Edit Edit Drop Drop Website BTREE No No Website (255) 491497 A YES Edit Edit Drop Drop Zip BTREE No No Zip (255) 178726 A YES Edit Edit Drop Drop Rating Star BTREE No No Rating Star 21 A YES Edit Edit Drop Drop Rating Weight BTREE No No Rating Weight 21 A YES Edit Edit Drop Drop Latitude BTREE No No Latitude 1965990 A YES Edit Edit Drop Drop Longitude BTREE No No Longitude 1965990 A YES The query took forever. I think there has to be something wrong there. Showing rows 0 - 29 ( 67,565 total, Query took 12.4767 sec)

    Read the article

  • unable to update gridview

    - by bhakti
    Please help ,i have added update/edit command button in gridview so to update data in my sql server database but am unable to do it. Data is not updated in database . ======code for onrowupdate======================================== protected void gRowUpdate(object sender, GridViewUpdateEventArgs e) { Books b = null; b = new Books(); DataTable dt=null; GridView g = (GridView)sender; try { dt=new DataTable(); b = new Books(); b.author = Convert.ToString(g.Rows[e.RowIndex].FindControl("Author")); b.bookID = Convert.ToInt32(g.Rows[e.RowIndex].FindControl("BookID")); b.title = Convert.ToString(g.Rows[e.RowIndex].FindControl("Title")); b.price = Convert.ToDouble(g.Rows[e.RowIndex].FindControl("Price")); // b.rec = Convert.ToString(g.Rows[e.RowIndex].FindControl("Date_of_reciept")); b.ed = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.bill = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.cre_by = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.src = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.pages = Convert.ToInt32(g.Rows[e.RowIndex].FindControl("Edition")); b.pub = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.mod_by = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.remark = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); // b.year = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.updatebook(b); g.EditIndex = -1; dt = b.GetAllBooks(); g.DataSource = dt; g.DataBind(); } catch (Exception ex) { throw (ex); } finally { b = null; } } ===================My stored procedure for update book able to update database by exec in sqlserver mgmt studio========================== set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go ALTER PROCEDURE [dbo].[usp_updatebook] @bookid bigint, @author varchar(50), @title varchar(50), @price bigint, @src_equisition varchar(50), @bill_no varchar(50), @publisher varchar(50), @pages bigint, @remark varchar(50), @edition varchar(50), @created_by varchar(50), @modified_by varchar(50) /*@date_of_reciept datetime, @year_of_publication datetime*/ AS declare @modified_on datetime set @modified_on=getdate() UPDATE books SET author=@author, title=@title, price=@price, src_equisition=@src_equisition, bill_no=@bill_no, publisher=@publisher, /*Date_of_reciept=@date_of_reciept,*/ pages=@pages, remark=@remark, edition=@edition, /*Year_of_publication=@year_of_publication,*/ created_by=@created_by, modified_on=@modified_on, modified_by=@modified_by WHERE bookid=@bookid ========================class library function for update==================== public void updatebook(Books b) { DataAccess dbAccess = null; SqlCommand cmd = null; try { dbAccess = new DataAccess(); cmd = dbAccess.GetSQLCommand("usp_updatebook", CommandType.StoredProcedure); cmd.Parameters.Add("@bookid", SqlDbType.VarChar, 50).Value = b.bookID; cmd.Parameters.Add("@author", SqlDbType.VarChar, 50).Value = b.author; cmd.Parameters.Add("@title", SqlDbType.VarChar, 50).Value = b.title; cmd.Parameters.Add("@price", SqlDbType.Money).Value = b.price; cmd.Parameters.Add("@publisher", SqlDbType.VarChar, 50).Value = b.pub; // cmd.Parameters.Add("@year_of_publication", SqlDbType.DateTime).Value =Convert.ToDateTime( b.year); cmd.Parameters.Add("@src_equisition", SqlDbType.VarChar, 50).Value = b.src; cmd.Parameters.Add("@bill_no", SqlDbType.VarChar, 50).Value = b.bill; cmd.Parameters.Add("@remark", SqlDbType.VarChar, 50).Value = b.remark; cmd.Parameters.Add("@pages", SqlDbType.Int).Value = b.pages; cmd.Parameters.Add("@edition", SqlDbType.VarChar, 50).Value = b.ed; // cmd.Parameters.Add("@date_of_reciept", SqlDbType.DateTime).Value = Convert.ToDateTime(b.rec); // cmd.Parameters.Add("@created_on", SqlDbType.DateTime).Value = Convert.ToDateTime(b.cre_on); cmd.Parameters.Add("@created_by", SqlDbType.VarChar, 50).Value = b.cre_by; //cmd.Parameters.Add("@modified_on", SqlDbType.DateTime).Value = Convert.ToDateTime(b.mod_on); cmd.Parameters.Add("@modified_by", SqlDbType.VarChar, 50).Value = b.mod_by; cmd.ExecuteNonQuery(); } catch (Exception ex) { throw (ex); } finally { if (cmd.Connection != null && cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close(); dbAccess = null; cmd = null; } } I have also tried to do update by following way protected void gv1_updating(object sender, GridViewUpdateEventArgs e) { GridView g = (GridView)sender; abc a = new abc(); DataTable dt = new DataTable(); try { a.cd_Id = Convert.ToInt32(g.DataKeys[e.RowIndex].Values[0].ToString()); //TextBox b = (TextBox)g.Rows[e.RowIndex].Cells[0].FindControl("cd_id"); TextBox c = (TextBox)g.Rows[e.RowIndex].Cells[2].FindControl("cd_name"); TextBox d = (TextBox)g.Rows[e.RowIndex].Cells[3].FindControl("version"); TextBox f = (TextBox)g.Rows[e.RowIndex].Cells[4].FindControl("company"); TextBox h = (TextBox)g.Rows[e.RowIndex].Cells[6].FindControl("created_by"); TextBox i = (TextBox)g.Rows[e.RowIndex].Cells[8].FindControl("modified_by"); //a.cd_Id = Convert.ToInt32(b.Text); a.cd_name = c.Text; a.ver = d.Text; a.comp = f.Text; a.cre_by = h.Text; a.mod_by = i.Text; a.updateDigi(a); g.EditIndex = -1; dt = a.GetAllDigi(); g.DataSource = dt; g.DataBind(); } catch(Exception ex) { throw (ex); } finally { dt = null; a = null; g = null; } } =================== but have error of Index out of range exception========= please do reply,thanxs in advance

    Read the article

  • STORED PROCEDURE working in my local test machine cannot be created in production environment.

    - by Marcos Buarque
    Hi, I have an SQL CREATE PROCEDURE statement that runs perfectly in my local SQL Server, but cannot be recreated in production environment. The error message I get in production is Msg 102, Level 15, State 1, Incorrect syntax near '='. It is a pretty big query and I don't want to annoy StackOverflow users, but I simply can't find a solution. If only you could point me out what settings I could check in the production server in order to enable running the code... I must be using some kind of syntax or something that is conflicting with some setting in production. This PROCEDURE was already registered in production before, but when I ran a DROP - CREATE PROCEDURE today, the server was able to drop the procedure, but not to recreate it. I will paste the code below. Thank you! =============== USE [Enorway] GO /****** Object: StoredProcedure [dbo].[Spel_CM_ChartsUsersTotals] Script Date: 03/17/2010 11:59:57 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROC [dbo].[Spel_CM_ChartsUsersTotals] @IdGroup int, @IdAssessment int, @UserId int AS SET NOCOUNT ON DECLARE @RequiredColor varchar(6) SET @RequiredColor = '3333cc' DECLARE @ManagersColor varchar(6) SET @ManagersColor = '993300' DECLARE @GroupColor varchar(6) SET @GroupColor = 'ff0000' DECLARE @SelfColor varchar(6) SET @SelfColor = '336600' DECLARE @TeamColor varchar(6) SET @TeamColor = '993399' DECLARE @intMyCounter tinyint DECLARE @intManagersPosition tinyint DECLARE @intGroupPosition tinyint DECLARE @intSelfPosition tinyint DECLARE @intTeamPosition tinyint SET @intMyCounter = 1 -- Table that will hold the subtotals... DECLARE @tblTotalsSource table ( IdCompetency int, CompetencyName nvarchar(200), FunctionRequiredLevel float, ManagersAverageAssessment float, SelfAssessment float, GroupAverageAssessment float, TeamAverageAssessment float ) INSERT INTO @tblTotalsSource ( IdCompetency, CompetencyName, FunctionRequiredLevel, ManagersAverageAssessment, SelfAssessment, GroupAverageAssessment, TeamAverageAssessment ) SELECT e.[IdCompetency], dbo.replaceAccentChar(e.[Name]) AS CompetencyName, (i.[LevelNumber]) AS FunctionRequiredLevel, ( SELECT ROUND(avg(CAST(ac.[LevelNumber] AS float)),0) FROM Spel_CM_AssessmentsData aa INNER JOIN Spel_CM_CompetenciesLevels ab ON aa.[IdCompetencyLevel] = ab.[IdCompetencyLevel] INNER JOIN Spel_CM_Levels ac ON ab.[IdLevel] = ac.[IdLevel] INNER JOIN Spel_CM_AssessmentsEvents ad ON aa.[IdAssessmentEvent] = ad.[IdAssessmentEvent] WHERE aa.[EvaluatedUserId] = @UserId AND aa.[AssessmentType] = 't' AND aa.[IdGroup] = @IdGroup AND ab.[IdCompetency] = e.[IdCompetency] AND ad.[IdAssessment] = @IdAssessment ) AS ManagersAverageAssessment, ( SELECT bc.[LevelNumber] FROM Spel_CM_AssessmentsData ba INNER JOIN Spel_CM_CompetenciesLevels bb ON ba.[IdCompetencyLevel] = bb.[IdCompetencyLevel] INNER JOIN Spel_CM_Levels bc ON bb.[IdLevel] = bc.[IdLevel] INNER JOIN Spel_CM_AssessmentsEvents bd ON ba.[IdAssessmentEvent] = bd.[IdAssessmentEvent] WHERE ba.[EvaluatedUserId] = @UserId AND ba.[AssessmentType] = 's' AND ba.[IdGroup] = @IdGroup AND bb.[IdCompetency] = e.[IdCompetency] AND bd.[IdAssessment] = @IdAssessment ) AS SelfAssessment, ( SELECT ROUND(avg(CAST(cc.[LevelNumber] AS float)),0) FROM Spel_CM_AssessmentsData ca INNER JOIN Spel_CM_CompetenciesLevels cb ON ca.[IdCompetencyLevel] = cb.[IdCompetencyLevel] INNER JOIN Spel_CM_Levels cc ON cb.[IdLevel] = cc.[IdLevel] INNER JOIN Spel_CM_AssessmentsEvents cd ON ca.[IdAssessmentEvent] = cd.[IdAssessmentEvent] WHERE ca.[EvaluatedUserId] = @UserId AND ca.[AssessmentType] = 'g' AND ca.[IdGroup] = @IdGroup AND cb.[IdCompetency] = e.[IdCompetency] AND cd.[IdAssessment] = @IdAssessment ) AS GroupAverageAssessment, ( SELECT ROUND(avg(CAST(dc.[LevelNumber] AS float)),0) FROM Spel_CM_AssessmentsData da INNER JOIN Spel_CM_CompetenciesLevels db ON da.[IdCompetencyLevel] = db.[IdCompetencyLevel] INNER JOIN Spel_CM_Levels dc ON db.[IdLevel] = dc.[IdLevel] INNER JOIN Spel_CM_AssessmentsEvents dd ON da.[IdAssessmentEvent] = dd.[IdAssessmentEvent] WHERE da.[EvaluatedUserId] = @UserId AND da.[AssessmentType] = 'm' AND da.[IdGroup] = @IdGroup AND db.[IdCompetency] = e.[IdCompetency] AND dd.[IdAssessment] = @IdAssessment ) AS TeamAverageAssessment FROM Spel_CM_AssessmentsData a INNER JOIN Spel_CM_AssessmentsEvents c ON a.[IdAssessmentEvent] = c.[IdAssessmentEvent] INNER JOIN Spel_CM_CompetenciesLevels d ON a.[IdCompetencyLevel] = d.[IdCompetencyLevel] INNER JOIN Spel_CM_Competencies e ON d.[IdCompetency] = e.[IdCompetency] INNER JOIN Spel_CM_Levels f ON d.[IdLevel] = f.[IdLevel] -- This will link with user's assigned functions INNER JOIN Spel_CM_FunctionsCompetenciesLevels g ON a.[IdFunction] = g.[IdFunction] INNER JOIN Spel_CM_CompetenciesLevels h ON g.[IdCompetencyLevel] = h.[IdCompetencyLevel] AND e.[IdCompetency] = h.[IdCompetency] INNER JOIN Spel_CM_Levels i ON h.[IdLevel] = i.[IdLevel] WHERE (NOT c.[EndDate] IS NULL) AND a.[EvaluatedUserId] = @UserId AND c.[IdAssessment] = @IdAssessment AND a.[IdGroup] = @IdGroup GROUP BY e.[IdCompetency], e.[Name], i.[LevelNumber] ORDER BY e.[Name] ASC -- This will define the position of each element (managers, group, self and team) SELECT @intManagersPosition = @intMyCounter FROM @tblTotalsSource WHERE NOT ManagersAverageAssessment IS NULL IF IsNumeric(@intManagersPosition) = 1 BEGIN SELECT @intMyCounter += 1 END SELECT @intGroupPosition = @intMyCounter FROM @tblTotalsSource WHERE NOT GroupAverageAssessment IS NULL IF IsNumeric(@intGroupPosition) = 1 BEGIN SELECT @intMyCounter += 1 END SELECT @intSelfPosition = @intMyCounter FROM @tblTotalsSource WHERE NOT SelfAssessment IS NULL IF IsNumeric(@intSelfPosition) = 1 BEGIN SELECT @intMyCounter += 1 END SELECT @intTeamPosition = @intMyCounter FROM @tblTotalsSource WHERE NOT TeamAverageAssessment IS NULL -- This will render the final table for the end user. The tabe will flatten some of the numbers to allow them to be prepared for Google Graphics. SELECT SUBSTRING( ( SELECT ( '|' + REPLACE(ma.[CompetencyName],' ','+')) FROM @tblTotalsSource ma ORDER BY ma.[CompetencyName] DESC FOR XML PATH('') ), 2, 1000) AS 'CompetenciesNames', SUBSTRING( ( SELECT ( ',' + REPLACE(ra.[FunctionRequiredLevel]*10,' ','+')) FROM @tblTotalsSource ra FOR XML PATH('') ), 2, 1000) AS 'FunctionRequiredLevel', SUBSTRING( ( SELECT ( ',' + CAST(na.[ManagersAverageAssessment]*10 AS nvarchar(10))) FROM @tblTotalsSource na FOR XML PATH('') ), 2, 1000) AS 'ManagersAverageAssessment', SUBSTRING( ( SELECT ( ',' + CAST(oa.[GroupAverageAssessment]*10 AS nvarchar(10))) FROM @tblTotalsSource oa FOR XML PATH('') ), 2, 1000) AS 'GroupAverageAssessment', SUBSTRING( ( SELECT ( ',' + CAST(pa.[SelfAssessment]*10 AS nvarchar(10))) FROM @tblTotalsSource pa FOR XML PATH('') ), 2, 1000) AS 'SelfAssessment', SUBSTRING( ( SELECT ( ',' + CAST(qa.[TeamAverageAssessment]*10 AS nvarchar(10))) FROM @tblTotalsSource qa FOR XML PATH('') ), 2, 1000) AS 'TeamAverageAssessment', SUBSTRING( ( SELECT ( '|t++' + CAST([FunctionRequiredLevel] AS varchar(10)) + ',' + @RequiredColor + ',0,' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',9') FROM @tblTotalsSource FOR XML PATH('') ), 2, 1000) AS 'FunctionRequiredAverageLabel', SUBSTRING( ( SELECT ( '|t++' + CAST([ManagersAverageAssessment] AS varchar(10)) + ',' + @ManagersColor + ',' + CAST(@intManagersPosition AS varchar(2)) + ',' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',9') FROM @tblTotalsSource FOR XML PATH('') ), 2, 1000) AS 'ManagersLabel', SUBSTRING( ( SELECT ( '|t++' + CAST([GroupAverageAssessment] AS varchar(10)) + ',' + @GroupColor + ',' + CAST(@intGroupPosition AS varchar(2)) + ',' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',9') FROM @tblTotalsSource FOR XML PATH('') ), 2, 1000) AS 'GroupLabel', SUBSTRING( ( SELECT ( '|t++' + CAST([SelfAssessment] AS varchar(10)) + ',' + @SelfColor + ',' + CAST(@intSelfPosition AS varchar(2)) + ',' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',9') FROM @tblTotalsSource FOR XML PATH('') ), 2, 1000) AS 'SelfLabel', SUBSTRING( ( SELECT ( '|t++' + CAST([TeamAverageAssessment] AS varchar(10)) + ',' + @TeamColor + ',' + CAST(@intTeamPosition AS varchar(2)) + ',' + CAST(ROW_NUMBER() OVER(ORDER BY CompetencyName) - 1 AS varchar(2)) + ',10') FROM @tblTotalsSource FOR XML PATH('') ), 2, 1000) AS 'TeamLabel', (Count(src.[IdCompetency]) * 30) + 100 AS 'ControlHeight' FROM @tblTotalsSource src SET NOCOUNT OFF GO

    Read the article

  • autoincrement in access sql is not working

    - by Thunder
    how can i create a table with autoincrement in access.Here is what i have been doing but not working. CREATE TABLE People_User_Master( Id INTEGER primary key AUTOINCREMENT , Name varchar(50) , LastName varchar(50) , Userid varchar(50) unique , Email varchar(50) , Phone varchar(50) , Pw varchar(50) , fk_Group int , Address varchar(150) )

    Read the article

  • SQL 2008 HierarchyID - Select X descendants down

    - by NTulip
    How can I query a table which has a column of data type HIERARCHYID and get a list of descendants X levels deep under an employee? Here is the current structure: CREATE TABLE [dbo].[Employees]( [NodeId] [hierarchyid] NOT NULL, [EmployeeId] [int] IDENTITY(1,1) NOT NULL, [FirstName] [varchar](120) NULL, [MiddleInitial] [varchar](1) NULL, [LastName] [varchar](120) NULL, [DepartmentId] [int] NULL, [Title] [varchar](120) NULL, [PhoneNumber] [varchar](20) NULL, [IM] [varchar](120) NULL, [Photo] [varbinary](max) NULL, [Bio] [varchar](400) NULL, [Active] [bit] NULL, [ManagerId] [int] NULL )

    Read the article

  • Coping with infrastructure upgrades

    - by Fatherjack
    A common topic for questions on SQL Server forums is how to plan and implement upgrades to SQL Server. Moving from old to new hardware or moving from one version of SQL Server to another. There are other circumstances where upgrades of other systems affect SQL Server DBAs. For example, where I work at the moment there is an Microsoft Exchange (email) server upgrade in progress. It it being handled by a different team so I’m not wholly sure on the details but we are in a situation where there are currently 2 Exchange email servers – the old one and the new one. Users mail boxes are being transferred in a planned process but as we approach the old server being turned off we have to also make sure that our SQL Servers get updated to use the new SMTP server for all of the SQL Agent notifications, SSIS packages etc. My servers have a number of profiles so that various jobs can send emails on behalf of various departments and different systems. This means there are lots of places that the old server name needs to be replaced by the new one. Anyone who has set up DBMail and enjoyed the click-tastic odyssey of screens to create Profiles and Accounts and so on and so forth ought to seek some professional help in my opinion. It’s a nightmare of back and forth settings changes and it stinks. I wasn’t looking forward to heading into this mess of a UI and changing the old Exchange server name for the new one on all my SQL Instances for all of the accounts I have set up. So I did what any Englishmen with a shed would do, I decided to take it apart and see if I can fix it another way. I took a guess that we are going to be working in MSDB and Books OnLine was remarkably helpful and amongst a lot of information told me about a couple of procedures that can be used to interrogate DBMail settings. USE [msdb] -- It's where all the good stuff is kept GO EXEC dbo.sysmail_help_profile_sp; EXEC dbo.sysmail_help_account_sp; Both of these procedures take optional parameters with the same name – ID and Name. If you provide an ID or a name then the results you get back are for that specific Profile or Account. Otherwise you get details of all Profiles and Accounts on the server you are connected to. As you can see (click for a bigger image), the Account has the SMTP server information in the servername column. We want to change that value to NewSMTP.Contoso.com. Now it appears that the procedure we are looking at gets it’s data from the sysmail_account and sysmail_server tables, you can get the results the stored procedure provides if you run the code below. SELECT [account_id] , [name] , [description] , [email_address] , [display_name] , [replyto_address] , [last_mod_datetime] , [last_mod_user] FROM dbo.sysmail_account AS sa; SELECT [account_id] , [servertype] , [servername] , [port] , [username] , [credential_id] , [use_default_credentials] , [enable_ssl] , [flags] , [last_mod_datetime] , [last_mod_user] , [timeout] FROM dbo.sysmail_server AS sms Now, we have no real idea how these tables are linked and whether making an update direct to one or other of them is going to do what we want or whether it will entirely cripple our ability to send email from SQL Server so we wont touch those tables with any UPDATE TSQL. So, back to Books OnLine then and we find sysmail_update_account_sp. It’s exactly what we need. The examples in BOL take the form (as below) of having every parameter explicitly defined. Not wanting to totally obliterate the existing values by not passing values in all of the parameters I set to writing some code to gather the existing data from the tables and re-write the SMTP server name and then execute the resulting TSQL. IF OBJECT_ID('tempdb..#sysmailprofiles') IS NOT NULL DROP TABLE #sysmailprofiles GO CREATE TABLE #sysmailprofiles ( account_id INT , [name] VARCHAR(50) , [description] VARCHAR(500) , email_address VARCHAR(500) , display_name VARCHAR(500) , replyto_address VARCHAR(500) , servertype VARCHAR(10) , servername VARCHAR(100) , port INT , username VARCHAR(100) , use_default_credentials VARCHAR(1) , ENABLE_ssl VARCHAR(1) ) INSERT [#sysmailprofiles] ( [account_id] , [name] , [description] , [email_address] , [display_name] , [replyto_address] , [servertype] , [servername] , [port] , [username] , [use_default_credentials] , [ENABLE_ssl] ) EXEC [dbo].[sysmail_help_account_sp] DECLARE @TSQL NVARCHAR(1000) SELECT TOP 1 @TSQL = 'EXEC [dbo].[sysmail_update_account_sp] @account_id = ' + CAST([s].[account_id] AS VARCHAR(20)) + ', @account_name = ''' + [s].[name] + '''' + ', @email_address = N''' + [s].[email_address] + '''' + ', @display_name = N''' + [s].[display_name] + '''' + ', @replyto_address = N''' + s.replyto_address + '''' + ', @description = N''' + [s].[description] + '''' + ', @mailserver_name = ''NEWSMTP.contoso.com''' + +', @mailserver_type = ' + [s].[servertype] + ', @port = ' + CAST([s].[port] AS VARCHAR(20)) + ', @username = ' + COALESCE([s].[username], '''''') + ', @use_default_credentials =' + CAST(s.[use_default_credentials] AS VARCHAR(1)) + ', @enable_ssl =' + [s].[ENABLE_ssl] FROM [#sysmailprofiles] AS s WHERE [s].[servername] = 'SMTP.Contoso.com' SELECT @tsql EXEC [sys].[sp_executesql] @tsql This worked well for me and testing the email function EXEC dbo.sp_send_dbmail afterwards showed that the settings were indeed using our new Exchange server. It was only later in writing this blog that I tried running the sysmail_update_account_sp procedure with only the SMTP server name parameter value specified. Despite what Books OnLine might intimate, you can do this and only the values for parameters specified get changed. If a parameter is not specified in the execution of the procedure then the values remain unchanged. This renders most of the above script unnecessary as I could have simply specified the account_id that I want to amend and the new value for the parameter I want to update. EXEC sysmail_update_account_sp @account_id = 1, @mailserver_name = 'NEWSMTP.Contoso.com' This wasn’t going to be the main reason for this post, it was meant to describe how to capture values from a stored procedure and use them in dynamic TSQL but instead we are here and (re)learning the fact that Books Online is a little flawed in places. It is a fantastic resource for anyone working with SQL Server but the reader must adopt an enquiring frame of mind and use a little curiosity to try simple variations on examples to fully understand the code you are working with. I think the author(s) of this part of Books OnLine missed an opportunity to include a third example that had fewer than all parameters specified to give a lead to this method existing.

    Read the article

  • Getting a Temporary Table Returned from from Dynamic SQL in SQL Server 05, and parsing

    - by gloomy.penguin
    So I was requested to make a few things.... (it is Monday morning and for some reason this whole thing is turning out to be really hard for me to explain so I am just going to try and post a lot of my code; sorry) First, I needed a table: CREATE TABLE TICKET_INFORMATION ( TICKET_INFO_ID INT IDENTITY(1,1) NOT NULL, TICKET_TYPE INT, TARGET_ID INT, TARGET_NAME VARCHAR(100), INFORMATION VARCHAR(MAX), TIME_STAMP DATETIME DEFAULT GETUTCDATE() ) -- insert this row for testing... INSERT INTO TICKET_INFORMATION (TICKET_TYPE, TARGET_ID, TARGET_NAME, INFORMATION) VALUES (1,1,'RT_ID','IF_ID,int=1&IF_ID,int=2&OTHER,varchar(10)=val,ue3&OTHER,varchar(10)=val,ue4') The Information column holds data that needs to be parsed into a table. This is where I am having problems. In the resulting table, Target_Name needs to become a column that holds Target_ID as a value for each row in the resulting table. The string that needs to be parsed is in this format: @var_name1,@var_datatype1=@var_value1&@var_name2,@var_datatype2=@var_value2&@var_name3,@var_datatype3=@var_value3 And what I ultimately need as a result (in a table or table variable): RT_ID IF_ID OTHER 1 1 val,ue3 1 2 val,ue3 1 1 val,ue4 1 2 val,ue4 And I need to be able to join on the result. Initially, I was just going to make this a function that returns a table variable but for some reason I can't figure out how to get it into an actual table variable. Whatever parses the string needs to be able to be used directly in queries so I don't think a stored procedure is really the right thing to be using. This is the code that parses the Information string... it returns in a temporary table. -- create/empty temp table for var_name, var_type and var_value fields if OBJECT_ID('tempdb..#temp') is not null drop table #temp create table #temp (row int identity(1,1), var_name varchar(max), var_type varchar(30), var_value varchar(max)) -- just setting stuff up declare @target_name varchar(max), @target_id varchar(max), @info varchar(max) set @target_name = (select target_name from ticket_information where ticket_info_id = 1) set @target_id = (select target_id from ticket_information where ticket_info_id = 1) set @info = (select information from ticket_information where ticket_info_id = 1) --print @info -- some of these variables are re-used later declare @col_type varchar(20), @query varchar(max), @select as varchar(max) set @query = 'select ' + @target_id + ' as ' + @target_name + ' into #target; ' set @select = 'select * into ##global_temp from #target' declare @var_name varchar(100), @var_type varchar(100), @var_value varchar(100) declare @comma_pos int, @equal_pos int, @amp_pos int set @comma_pos = 1 set @equal_pos = 1 set @amp_pos = 0 -- while loop to parse the string into a table while @amp_pos < len(@info) begin -- get new comma position set @comma_pos = charindex(',',@info,@amp_pos+1) -- get new equal position set @equal_pos = charindex('=',@info,@amp_pos+1) -- set stuff that is going into the table set @var_name = substring(@info,@amp_pos+1,@comma_pos-@amp_pos-1) set @var_type = substring(@info,@comma_pos+1,@equal_pos-@comma_pos-1) -- get new ampersand position set @amp_pos = charindex('&',@info,@amp_pos+1) if @amp_pos=0 or @amp_pos<@equal_pos set @amp_pos = len(@info)+1 -- set last variable for insert into table set @var_value = substring(@info,@equal_pos+1,@amp_pos-@equal_pos-1) -- put stuff into the temp table insert into #temp (var_name, var_type, var_value) values (@var_name, @var_type, @var_value) -- is this a new field? if ((select count(*) from #temp where var_name = (@var_name)) = 1) begin set @query = @query + ' create table #' + @var_name + '_temp (' + @var_name + ' ' + @var_type + '); ' set @select = @select + ', #' + @var_name + '_temp ' end set @query = @query + ' insert into #' + @var_name + '_temp values (''' + @var_value + '''); ' end if OBJECT_ID('tempdb..##global_temp') is not null drop table ##global_temp exec (@query + @select) --select @query --select @select select * from ##global_temp Okay. So, the result I want and need is now in ##global_temp. How do I put all of that into something that can be returned from a function (or something)? Or can I get something more useful returned from the exec statement? In the end, the results of the parsed string need to be in a table that can be joined on and used... Ideally this would have been a view but I guess it can't with all the processing that needs to be done on that information string. Ideas? Thanks!

    Read the article

  • How to determine if you should use full or differential backup?

    - by Peter Larsson
    Or ask yourself, "How much of the database has changed since last backup?". Here is a simple script that will tell you how much (in percent) have changed in the database since last backup. -- Prepare staging table for all DBCC outputs DECLARE @Sample TABLE         (             Col1 VARCHAR(MAX) NOT NULL,             Col2 VARCHAR(MAX) NOT NULL,             Col3 VARCHAR(MAX) NOT NULL,             Col4 VARCHAR(MAX) NOT NULL,             Col5 VARCHAR(MAX)         )   -- Some intermediate variables for controlling loop DECLARE @FileNum BIGINT = 1,         @PageNum BIGINT = 6,         @SQL VARCHAR(100),         @Error INT,         @DatabaseName SYSNAME = 'Yoda'   -- Loop all files to the very end WHILE 1 = 1     BEGIN         BEGIN TRY             -- Build the SQL string to execute             SET     @SQL = 'DBCC PAGE(' + QUOTENAME(@DatabaseName) + ', ' + CAST(@FileNum AS VARCHAR(50)) + ', '                             + CAST(@PageNum AS VARCHAR(50)) + ', 3) WITH TABLERESULTS'               -- Insert the DBCC output in the staging table             INSERT  @Sample                     (                         Col1,                         Col2,                         Col3,                         Col4                     )             EXEC    (@SQL)               -- DCM pages exists at an interval             SET    @PageNum += 511232         END TRY           BEGIN CATCH             -- If error and first DCM page does not exist, all files are read             IF @PageNum = 6                 BREAK             ELSE                 -- If no more DCM, increase filenum and start over                 SELECT  @FileNum += 1,                         @PageNum = 6         END CATCH     END   -- Delete all records not related to diff information DELETE FROM    @Sample WHERE   Col1 NOT LIKE 'DIFF%'   -- Split the range UPDATE  @Sample SET     Col5 = PARSENAME(REPLACE(Col3, ' - ', '.'), 1),         Col3 = PARSENAME(REPLACE(Col3, ' - ', '.'), 2)   -- Remove last paranthesis UPDATE  @Sample SET     Col3 = RTRIM(REPLACE(Col3, ')', '')),         Col5 = RTRIM(REPLACE(Col5, ')', ''))   -- Remove initial information about filenum UPDATE  @Sample SET     Col3 = SUBSTRING(Col3, CHARINDEX(':', Col3) + 1, 8000),         Col5 = SUBSTRING(Col5, CHARINDEX(':', Col5) + 1, 8000)   -- Prepare data outtake ;WITH cteSource(Changed, [PageCount]) AS (     SELECT      Changed,                 SUM(COALESCE(ToPage, FromPage) - FromPage + 1) AS [PageCount]     FROM        (                     SELECT CAST(Col3 AS INT) AS FromPage,                             CAST(NULLIF(Col5, '') AS INT) AS ToPage,                             LTRIM(Col4) AS Changed                     FROM    @Sample                 ) AS d     GROUP BY    Changed     WITH ROLLUP ) -- Present the final result SELECT  COALESCE(Changed, 'TOTAL PAGES') AS Changed,         [PageCount],         100.E * [PageCount] / SUM(CASE WHEN Changed IS NULL THEN 0 ELSE [PageCount] END) OVER () AS Percentage FROM    cteSource

    Read the article

  • python MySQLdb got invalid syntax when trying to INSERT INTO table

    - by Michelle Jun Lee
    ## COMMENT OUT below just for reference "" cursor.execute (""" CREATE TABLE yellowpages ( business_id BIGINT(20) NOT NULL AUTO_INCREMENT, categories_name VARCHAR(255), business_name VARCHAR(500) NOT NULL, business_address1 VARCHAR(500), business_city VARCHAR(255), business_state VARCHAR(255), business_zipcode VARCHAR(255), phone_number1 VARCHAR(255), website1 VARCHAR(1000), website2 VARCHAR(1000), created_date datetime, modified_date datetime, PRIMARY KEY(business_id) ) """) "" ## TOP COMMENT OUT (just for reference) ## code website1g = "http://www.triman.com" business_nameg = "Triman Sales Inc" business_address1g = "510 E Airline Way" business_cityg = "Gardena" business_stateg = "CA" business_zipcodeg = "90248" phone_number1g = "(310) 323-5410" phone_number2g = "" website2g = "" cursor.execute (""" INSERT INTO yellowpages(categories_name, business_name, business_address1, business_city, business_state, business_zipcode, phone_number1, website1, website2) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s') """, (''gas-stations'', business_nameg, business_address1g, business_cityg, business_stateg, business_zipcodeg, phone_number1g, website1g, website2g)) cursor.close() conn.close() I keep getting this error File "testdb.py", line 51 """, (''gas-stations'', business_nameg, business_address1g, business_cityg, business_stateg, business_zipcodeg, phone_number1g, website1g, website2g)) ^ SyntaxError: invalid syntax any idea why? By the way, the up arrow is pointing to website1g (the b character) . Thanks for the help in advance

    Read the article

  • Msdtc Transaction

    - by Shimjith
    I am using Linked server For Tansaction example Alter Proc [dbo].[usp_Select_TransferingDatasFromServerCheckingforExample] @RserverName varchar(100), ----- Server Name @RUserid Varchar(100), ----- server user id @RPass Varchar(100), ----- Server Password @DbName varchar(100) ----- Server database As Set nocount on Set Xact_abort on Declare @user varchar(100) Declare @userID varchar(100) Declare @Db Varchar(100) Declare @Lserver varchar(100) Select @Lserver = @@servername Select @userID = suser_name() select @User=user Exec('if exists(Select 1 From [Master].[' + @user + '].[sysservers] where srvname = ''' + @RserverName + ''') begin Exec sp_droplinkedsrvlogin ''' + @RserverName + ''',''' + @userID + ''' exec sp_dropserver ''' + @RserverName + ''' end ') set @RserverName='['+@RserverName+']' BEGIN TRY BEGIN TRANSACTION declare @ColumnList varchar(max) set @ColumnList = null select @ColumnList = case when @ColumnList is not null then @ColumnList + ',' + quotename(name) else quotename(name) end from syscolumns where id = object_id('bditm') order by colid set identity_insert Bditm on exec ('Insert Into Bditm ('+ @ColumnList +') Select * From '+ @RserverName + '.'+ @DbName + '.'+ @user + '.Bditm') set identity_insert Bditm off Commit Select 1 End try Begin catch if (@@ERROR < 0) Begin if @@trancount 0 Begin Rollback transaction Select 0 END End End Catch set @RserverName=replace(replace(@RserverName,'[',''),']','') Exec sp_droplinkedsrvlogin @RserverName,@userID Exec sp_dropserver @RserverName this is the Error Occuerd The Microsoft Distributed Transaction Coordinator (MS DTC) has cancelled the distributed transaction.

    Read the article

  • i need to use string variable in the Proc in sql server database 2005

    - by bassam
    I have this procedure CREATE Proc [dbo].Salse_Ditail -- Add the parameters for the stored procedure here @Report_Form varchar(1) , @DateFrom datetime , @DateTo datetime , @COMPANYID varchar(3), @All varchar(1) , @All1 varchar(1) , @All2 varchar(1) , @All3 varchar(1) , @All4 varchar(1) , @All5 varchar(1) , @Sector varchar(10), @Report_Parameter nvarchar(max) as BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. DECLARE @STRWhere nvarchar(max) IF @All5=0 AND @All4=0 AND @All3=0 AND @All2=0 AND @All1=0 and @All=1 set @STRWhere= N'and Sector_id = @Sector' if @Report_Form =1 or @Report_Form =3 or @Report_Form =4 SELECT RETURNREASONCODEID, SITE,SITE_NAME,Factory_id,Factory_Name,Sector_id,sector_name,Customer_name, Customer_id,ITEMID,ITEMNAME,SALESMANID,SALESMAN_NAME,Net_Qty,Net_Salse,Gross_Sales,Gross_Qty, NETWEIGHT_Gross,NETWEIGHT_salse_Gross,NETWEIGHT_NET,NETWEIGHT_salse_NET,Return_Sales,Free_Good, CollectionAmount FROM hal_bas_new_rep WHERE DATAAREAID =@COMPANYID AND INVOICEDATE >= @DateFrom AND INVOICEDATE <= @DateTo and Report_Activti = @Report_Form if @Report_Form =2 SELECT RETURNREASONCODEID , RETURNREASONDESC, SITE , SITE_NAME , Factory_id , Factory_Name , Sector_id , sector_name , Customer_name , Customer_id , ITEMID , ITEMNAME , SALESMANID , SALESMAN_NAME , Return_Sales FROM dbo.hal_bas_new_rep WHERE DATAAREAID =@COMPANYID AND INVOICEDATE >= @DateFrom AND INVOICEDATE <= @DateTo and Report_Activti = @Report_Form and RETURNREASONCODEID in ( SELECT Val FROM dbo.fn_String_To_Table(@Report_Parameter,',',1) ) /* @STRWhere // question: how can I use the variable here? */ end GO As you see I'm constructing a condition for the WHERE clause in a variable, but I don't know how to use it.

    Read the article

  • i need to use string virble in the Proc in sql server database 2005

    - by bassam
    i have this Proc CREATE Proc [dbo].Salse_Ditail -- Add the parameters for the stored procedure here @Report_Form varchar(1) , @DateFrom datetime , @DateTo datetime , @COMPANYID varchar(3), @All varchar(1) , @All1 varchar(1) , @All2 varchar(1) , @All3 varchar(1) , @All4 varchar(1) , @All5 varchar(1) , @Sector varchar(10), @Report_Parameter nvarchar(max) as BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. DECLARE @STRWhere nvarchar(max) IF @All5=0 AND @All4=0 AND @All3=0 AND @All2=0 AND @All1=0 and @All=1 set @STRWhere= N'and Sector_id = @Sector' if @Report_Form =1 or @Report_Form =3 or @Report_Form =4 SELECT RETURNREASONCODEID, SITE,SITE_NAME,Factory_id,Factory_Name,Sector_id,sector_name,Customer_name, Customer_id,ITEMID,ITEMNAME,SALESMANID,SALESMAN_NAME,Net_Qty,Net_Salse,Gross_Sales,Gross_Qty, NETWEIGHT_Gross,NETWEIGHT_salse_Gross,NETWEIGHT_NET,NETWEIGHT_salse_NET,Return_Sales,Free_Good, CollectionAmount FROM hal_bas_new_rep WHERE DATAAREAID =@COMPANYID AND INVOICEDATE >= @DateFrom AND INVOICEDATE <= @DateTo and Report_Activti = @Report_Form if @Report_Form =2 SELECT RETURNREASONCODEID , RETURNREASONDESC, SITE , SITE_NAME , Factory_id , Factory_Name , Sector_id , sector_name , Customer_name , Customer_id , ITEMID , ITEMNAME , SALESMANID , SALESMAN_NAME , Return_Sales FROM dbo.hal_bas_new_rep WHERE DATAAREAID =@COMPANYID AND INVOICEDATE >= @DateFrom AND INVOICEDATE <= @DateTo and Report_Activti = @Report_Form and RETURNREASONCODEID in ( SELECT Val FROM dbo.fn_String_To_Table(@Report_Parameter,',',1) ) /* @STRWhere question how i can but the virble here */ end GO i want to but virble put a variable under where Expression and from this function buc I have many function i want to add if any one have answer pls send me

    Read the article

  • question in sql server 2005 Proc

    - by bassam
    i have this Proc CREATE Proc [dbo].Salse_Ditail -- Add the parameters for the stored procedure here @Report_Form varchar(1) , @DateFrom datetime , @DateTo datetime , @COMPANYID varchar(3), @All varchar(1) , @All1 varchar(1) , @All2 varchar(1) , @All3 varchar(1) , @All4 varchar(1) , @All5 varchar(1) , @Sector varchar(10), @Report_Parameter nvarchar(max) as BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. DECLARE @STRWhere nvarchar(max) IF @All5=0 AND @All4=0 AND @All3=0 AND @All2=0 AND @All1=0 and @All=1 set @STRWhere= N'and Sector_id = @Sector' if @Report_Form =1 or @Report_Form =3 or @Report_Form =4 SELECT RETURNREASONCODEID, SITE,SITE_NAME,Factory_id,Factory_Name,Sector_id,sector_name,Customer_name, Customer_id,ITEMID,ITEMNAME,SALESMANID,SALESMAN_NAME,Net_Qty,Net_Salse,Gross_Sales,Gross_Qty, NETWEIGHT_Gross,NETWEIGHT_salse_Gross,NETWEIGHT_NET,NETWEIGHT_salse_NET,Return_Sales,Free_Good, CollectionAmount FROM hal_bas_new_rep WHERE DATAAREAID =@COMPANYID AND INVOICEDATE >= @DateFrom AND INVOICEDATE <= @DateTo and Report_Activti = @Report_Form if @Report_Form =2 SELECT RETURNREASONCODEID , RETURNREASONDESC, SITE , SITE_NAME , Factory_id , Factory_Name , Sector_id , sector_name , Customer_name , Customer_id , ITEMID , ITEMNAME , SALESMANID , SALESMAN_NAME , Return_Sales FROM dbo.hal_bas_new_rep WHERE DATAAREAID =@COMPANYID AND INVOICEDATE >= @DateFrom AND INVOICEDATE <= @DateTo and Report_Activti = @Report_Form and RETURNREASONCODEID in ( SELECT Val FROM dbo.fn_String_To_Table(@Report_Parameter,',',1) ) /* @STRWhere question how i can but the virble here */ end GO i want to but virble put a variable under where Expression and from this function buc I have many function i want to add if any one have answer pls send me

    Read the article

  • how do i insert into two table all at once in a stored procedure?

    - by user996502
    Doing a project for school so any help would be great thank you! I have two tables how do i insert into two tables? so both tables are linked. First table called Customer with primary key called CID that auto increments CREATE TABLE [dbo].[Customer]( [CID] [int] IDENTITY(1,1) NOT NULL, [LastName] [varchar](255) NOT NULL, [FirstName] [varchar](255) NOT NULL, [MiddleName] [varchar](255) NULL, [EmailAddress] [varchar](255) NOT NULL, [PhoneNumber] [varchar](12) NOT NULL CONSTRAINT [PK__CInforma__C1F8DC5968DD69DC] PRIMARY KEY CLUSTERED ( And a second table called Employment that has a foreign key linked to the parent table CREATE TABLE [dbo].[Employment]( [EID] [int] IDENTITY(1,1) NOT NULL, [CID] [int] NOT NULL, [Employer] [varchar](255) NOT NULL, [Occupation] [varchar](255) NOT NULL, [Income] [varchar](25) NOT NULL, [WPhone] [varchar](12) NOT NULL, CONSTRAINT [PK__Employme__C190170BC7827524] PRIMARY KEY CLUSTERED (

    Read the article

  • Processing a resultset to look up foriegn keys (and poulate a new table!)

    - by Gilly
    Hi, I've been handed a dataset that has some fairly basic table structures with no keys at all. eg {myRubishTable} - Area(varchar),AuthorityName(varchar),StartYear(varchar),StartMonth(varcha),EndYear(varchar),EndMonth(varchar),Amount(Money) there are other tables that use the Area and AuthorityName columns as well as a general use of Month and Years so I I figured a good first step was to pull Area and Authority into their own tables. I now want to process the data in the original table and lookup the key value to put into my new table with foreign keys which looks like this. (lookup Tables) {Area} - id (int, PK), name (varchar(50)) {AuthorityName} - id(int, PK), name(varchar(50) (TargetTable) {myBetterTable} - id (int,PK), area_id(int FK-Area),authority_name_id(int FK-AuthorityName),StartYear (varchar),StartMonth(varchar),EndYear(varchar),EndMonth(varchar),Amount(money) so row one in the old table read MYAREA, MYAUTHORITY,2009,Jan,2010,Feb,10000 and I want to populate the new table with 1,1,1,2009,Jan,2010,Feb,10000 where the first '1' is the primary key and the second two '1's are the ids in the lookup tables. Can anyone point me to the most efficient way of achieving this using just SQL? Thanks in advance Footnote:- I've achieved what I needed with some pretty simple WHERE clauses (I had left a rogue tablename in the FROM which was throwing me :o( ) but would be interested to know if this is the most efficient. ie SELECT [area].[area_id], [authority].[authority_name_id], [myRubishTable].[StartYear], [myRubishTable].[StartMonth], [myRubishTable].[EndYear], [myRubishTable].[EndMonth], [myRubishTable].[Amount] FROM [myRubishTable],[Area],[AuthorityName] WHERE [myRubishTable].[Area]=[Area].[name] AND [myRubishTable].[Authority Name]=[dim_AuthorityName].[name] TIA

    Read the article

  • How to get the Output value of SP using C#

    - by karthik
    I am using the following Code to execute the SP of MySql and get the output value. I need to get the output value to my c# after SP is executed. How ? Thanks. Code : public static string GetInsertStatement(string DBName, string TblName, string ColName, string ColValue) { string strData = ""; MySqlConnection conn = new MySqlConnection(ConfigurationSettings.AppSettings["Con_Admin"]); MySqlCommand cmd = conn.CreateCommand(); try { cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "InsGen"; cmd.Parameters.Clear(); cmd.Parameters.Add("in_db", MySqlDbType.VarChar, 20); cmd.Parameters["in_db"].Value = DBName; cmd.Parameters.Add("in_table", MySqlDbType.VarChar, 20); cmd.Parameters["in_table"].Value = TblName; cmd.Parameters.Add("in_ColumnName", MySqlDbType.VarChar, 20); cmd.Parameters["in_ColumnName"].Value = ColName; cmd.Parameters.Add("in_ColumnValue", MySqlDbType.VarChar, 20); cmd.Parameters["in_ColumnValue"].Value = ColValue; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } catch (System.Exception e) { Console.WriteLine(e.Message); } return strData; } SP : DELIMITER $$ DROP PROCEDURE IF EXISTS `InsGen` $$ CREATE DEFINER=`root`@`localhost` PROCEDURE `InsGen` ( in_db varchar(20), in_table varchar(20), in_ColumnName varchar(20), in_ColumnValue varchar(20) ) BEGIN declare Whrs varchar(500); declare Sels varchar(500); declare Inserts varchar(2000); declare tablename varchar(20); declare ColName varchar(20); set tablename=in_table; # Comma separated column names - used for Select select group_concat(concat('concat(\'"\',','ifnull(',column_name,','''')',',\'"\')')) INTO @Sels from information_schema.columns where table_schema=in_db and table_name=tablename; # Comma separated column names - used for Group By select group_concat('`',column_name,'`') INTO @Whrs from information_schema.columns where table_schema=in_db and table_name=tablename; #Main Select Statement for fetching comma separated table values set @Inserts=concat("select concat('insert into ", in_db,".",tablename," values(',concat_ws(',',",@Sels,"),');') from ", in_db,".",tablename, " where ", in_ColumnName, " = " , in_ColumnValue, " group by ",@Whrs, ";"); PREPARE Inserts FROM @Inserts; select Inserts; EXECUTE Inserts; END $$ DELIMITER ;

    Read the article

  • How to convert a datetime value into a varchar with MM/dd/yyyy HH:MM:SS AM/PM format?

    - by Jyina
    I need to convert the below date into the output as shown. I can get the date part using the code 101 but for the time I could not find any code that translates the time to HH:MM:SS AM/PM? Any ideas please? Thank you! declare @adddate datetime Set @adddate = 2011-07-06T22:30:07.5205649-04:00 Convert(varchar, @adddate, 101) + ' ' + Convert(varchar, @adddate, 108) The output should be 06/07/2011 10:30:07 PM

    Read the article

  • SQL SERVER – Display Datetime in Specific Format – SQL in Sixty Seconds #033 – Video

    - by pinaldave
    A very common requirement of developers is to format datetime to their specific need. Every geographic location has different need of the date formats. Some countries follow the standard of mm/dd/yy and some countries as dd/mm/yy. The need of developer changes as geographic location changes. In SQL Server there are various functions to aid this requirement. There is function CAST, which developers have been using for a long time as well function CONVERT which is a more enhanced version of CAST. In the latest version of SQL Server 2012 a new function FORMAT is introduced as well. In this SQL in Sixty Seconds video we cover two different methods to display the datetime in specific format. 1) CONVERT function and 2) FORMAT function. Let me know what you think of this video. Here is the script which is used in the video: -- http://blog.SQLAuthority.com -- SQL Server 2000/2005/2008/2012 onwards -- Datetime SELECT CONVERT(VARCHAR(30),GETDATE()) AS DateConvert; SELECT CONVERT(VARCHAR(30),GETDATE(),10) AS DateConvert; SELECT CONVERT(VARCHAR(30),GETDATE(),110) AS DateConvert; SELECT CONVERT(VARCHAR(30),GETDATE(),5) AS DateConvert; SELECT CONVERT(VARCHAR(30),GETDATE(),105) AS DateConvert; SELECT CONVERT(VARCHAR(30),GETDATE(),113) AS DateConvert; SELECT CONVERT(VARCHAR(30),GETDATE(),114) AS DateConvert; GO -- SQL Server 2012 onwards -- Various format of Datetime SELECT CONVERT(VARCHAR(30),GETDATE(),113) AS DateConvert; SELECT FORMAT ( GETDATE(), 'dd mon yyyy HH:m:ss:mmm', 'en-US' ) AS DateConvert; SELECT CONVERT(VARCHAR(30),GETDATE(),114) AS DateConvert; SELECT FORMAT ( GETDATE(), 'HH:m:ss:mmm', 'en-US' ) AS DateConvert; GO -- Specific usage of Format function SELECT FORMAT(GETDATE(), N'"Current Time is "dddd MMMM dd, yyyy', 'en-US') AS CurrentTimeString; This video discusses CONVERT and FORMAT in simple manner but the subject is much deeper and there are lots of information to cover along with it. I strongly suggest that you go over related blog posts in next section as there are wealth of knowledge discussed there. Related Tips in SQL in Sixty Seconds: Get Date and Time From Current DateTime – SQL in Sixty Seconds #025 Retrieve – Select Only Date Part From DateTime – Best Practice Get Time in Hour:Minute Format from a Datetime – Get Date Part Only from Datetime DATE and TIME in SQL Server 2008 Function to Round Up Time to Nearest Minutes Interval Get Date Time in Any Format – UDF – User Defined Functions Retrieve – Select Only Date Part From DateTime – Best Practice – Part 2 Difference Between DATETIME and DATETIME2 Saturday Fun Puzzle with SQL Server DATETIME2 and CAST What would you like to see in the next SQL in Sixty Seconds video? Reference: Pinal Dave (http://blog.sqlauthority.com)   Filed under: Database, Pinal Dave, PostADay, SQL, SQL Authority, SQL in Sixty Seconds, SQL Query, SQL Scripts, SQL Server, SQL Server Management Studio, SQL Tips and Tricks, T SQL, Technology, Video Tagged: Excel

    Read the article

  • Event Logging in LINQ C# .NET

    The first thing you'll want to do before using this code is to create a table in your database called TableHistory: CREATE TABLE [dbo].[TableHistory] (     [TableHistoryID] [int] IDENTITY NOT NULL ,     [TableName] [varchar] (50) NOT NULL ,     [Key1] [varchar] (50) NOT NULL ,     [Key2] [varchar] (50) NULL ,     [Key3] [varchar] (50) NULL ,     [Key4] [varchar] (50) NULL ,     [Key5] [varchar] (50) NULL ,     [Key6] [varchar] (50)NULL ,     [ActionType] [varchar] (50) NULL ,     [Property] [varchar] (50) NULL ,     [OldValue] [varchar] (8000) NULL ,     [NewValue] [varchar] (8000) NULL ,     [ActionUserName] [varchar] (50) NOT NULL ,     [ActionDateTime] [datetime] NOT NULL ) Once you have created the table, you'll need to add it to your custom LINQ class (which I will refer to as DboDataContext), thus creating the TableHistory class. Then, you'll need to add the History.cs file to your project. You'll also want to add the following code to your project to get the system date: public partial class DboDataContext{ [Function(Name = "GetDate", IsComposable = true)] public DateTime GetSystemDate() { MethodInfo mi = MethodBase.GetCurrentMethod() as MethodInfo; return (DateTime)this.ExecuteMethodCall(this, mi, new object[] { }).ReturnValue; }}private static Dictionary<type,> _cachedIL = new Dictionary<type,>();public static T CloneObjectWithIL<t>(T myObject){ Delegate myExec = null; if (!_cachedIL.TryGetValue(typeof(T), out myExec)) { // Create ILGenerator DynamicMethod dymMethod = new DynamicMethod("DoClone", typeof(T), new Type[] { typeof(T) }, true); ConstructorInfo cInfo = myObject.GetType().GetConstructor(new Type[] { }); ILGenerator generator = dymMethod.GetILGenerator(); LocalBuilder lbf = generator.DeclareLocal(typeof(T)); //lbf.SetLocalSymInfo("_temp"); generator.Emit(OpCodes.Newobj, cInfo); generator.Emit(OpCodes.Stloc_0); foreach (FieldInfo field in myObject.GetType().GetFields( System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)) { // Load the new object on the eval stack... (currently 1 item on eval stack) generator.Emit(OpCodes.Ldloc_0); // Load initial object (parameter) (currently 2 items on eval stack) generator.Emit(OpCodes.Ldarg_0); // Replace value by field value (still currently 2 items on eval stack) generator.Emit(OpCodes.Ldfld, field); // Store the value of the top on the eval stack into // the object underneath that value on the value stack. // (0 items on eval stack) generator.Emit(OpCodes.Stfld, field); } // Load new constructed obj on eval stack -> 1 item on stack generator.Emit(OpCodes.Ldloc_0); // Return constructed object. --> 0 items on stack generator.Emit(OpCodes.Ret); myExec = dymMethod.CreateDelegate(typeof(Func<t,>)); _cachedIL.Add(typeof(T), myExec); } return ((Func<t,>)myExec)(myObject);}I got both of the above methods off of the net somewhere (maybe even from CodeProject), but it's been long enough that I can't recall where I got them.Explanation of the History ClassThe History class records changes by creating a TableHistory record, inserting the values for the primary key for the table being modified into the Key1, Key2, ..., Key6 columns (if you have more than 6 values that make up a primary key on any table, you'll want to modify this), setting the type of change being made in the ActionType column (INSERT, UPDATE, or DELETE), old value and new value if it happens to be an update action, and the date and Windows identity of the user who made the change.Let's examine what happens when a call is made to the RecordLinqInsert method:public static void RecordLinqInsert(DboDataContext dbo, IIdentity user, object obj){ TableHistory hist = NewHistoryRecord(obj); hist.ActionType = "INSERT"; hist.ActionUserName = user.Name; hist.ActionDateTime = dbo.GetSystemDate(); dbo.TableHistories.InsertOnSubmit(hist);}private static TableHistory NewHistoryRecord(object obj){ TableHistory hist = new TableHistory(); Type type = obj.GetType(); PropertyInfo[] keys; if (historyRecordExceptions.ContainsKey(type)) { keys = historyRecordExceptions[type].ToArray(); } else { keys = type.GetProperties().Where(o => AttrIsPrimaryKey(o)).ToArray(); } if (keys.Length > KeyMax) throw new HistoryException("object has more than " + KeyMax.ToString() + " keys."); for (int i = 1; i <= keys.Length; i++) { typeof(TableHistory) .GetProperty("Key" + i.ToString()) .SetValue(hist, keys[i - 1].GetValue(obj, null).ToString(), null); } hist.TableName = type.Name; return hist;}protected static bool AttrIsPrimaryKey(PropertyInfo pi){ var attrs = from attr in pi.GetCustomAttributes(typeof(ColumnAttribute), true) where ((ColumnAttribute)attr).IsPrimaryKey select attr; if (attrs != null && attrs.Count() > 0) return true; else return false;}RecordLinqInsert takes as input a data context which it will use to write to the database, the user, and the LINQ object to be recorded (a single object, for instance, a Customer or Order object if you're using AdventureWorks). It then calls the NewHistoryRecord method, which uses LINQ to Objects in conjunction with the AttrIsPrimaryKey method to pull all the primary key properties, set the Key1-KeyN properties of the TableHistory object, and return the new TableHistory object. The code would be called in an application, like so: Continue span.fullpost {display:none;}

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >