How do I create the ELMAH SQL Server database? I added it to my ASP.NET MVC project through NuGet and don't have the sql script on my machine.
The DDL script is linked from the Elmah downloads page. No need to trawl the source tree.
(Why it's not bundled with the NuGet escapes me)
I found the script in source control: https://code.google.com/p/elmah/source/browse/src/Elmah.SqlServer/SQLServer.sql
Run that script on the database you are using to create the database structures for Elmah.
For a code first migration scenario, I found the this article very helpful.
First run Add-Migration AddElmah command in 'Package Manager Console'. This will create a file under Migration folder. This file will contain AddElmah class with to functions Up() and Down(). Replaced these two functions with below code:
public override void Up()
{
Sql(#"CREATE TABLE [dbo].[ELMAH_Error]
(
[ErrorId] UNIQUEIDENTIFIER NOT NULL,
[Application] NVARCHAR(60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Host] NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Type] NVARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Source] NVARCHAR(60) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Message] NVARCHAR(500) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[User] NVARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[StatusCode] INT NOT NULL,
[TimeUtc] DATETIME NOT NULL,
[Sequence] INT IDENTITY(1, 1) NOT NULL,
[AllXml] NTEXT COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ");
Sql("EXEC('ALTER TABLE [dbo].[ELMAH_Error] WITH NOCHECK ADD CONSTRAINT[PK_ELMAH_Error] PRIMARY KEY([ErrorId])')");
Sql("EXEC('ALTER TABLE [dbo].[ELMAH_Error] ADD CONSTRAINT[DF_ELMAH_Error_ErrorId] DEFAULT(NEWID()) FOR[ErrorId]')");
Sql(#"EXEC('CREATE NONCLUSTERED INDEX [IX_ELMAH_Error_App_Time_Seq] ON [dbo].[ELMAH_Error]
(
[Application] ASC,
[TimeUtc] DESC,
[Sequence] DESC
)')");
Sql(#"EXEC('CREATE PROCEDURE [dbo].[ELMAH_GetErrorXml] (#Application NVARCHAR(60), #ErrorId UNIQUEIDENTIFIER) AS
SET NOCOUNT ON
SELECT [AllXml] FROM [ELMAH_Error] WHERE [ErrorId] = #ErrorId AND [Application] = #Application')");
Sql(#"EXEC('CREATE PROCEDURE [dbo].[ELMAH_GetErrorsXml]
(#Application NVARCHAR(60), #PageIndex INT = 0, #PageSize INT = 15, #TotalCount INT OUTPUT)
AS
SET NOCOUNT ON
DECLARE #FirstTimeUTC DATETIME
DECLARE #FirstSequence INT
DECLARE #StartRow INT
DECLARE #StartRowIndex INT
SELECT #TotalCount = COUNT(1) FROM [ELMAH_Error] WHERE [Application] = #Application
SET #StartRowIndex = #PageIndex * #PageSize + 1
IF #StartRowIndex <= #TotalCount
BEGIN
SET ROWCOUNT #StartRowIndex
SELECT #FirstTimeUTC = [TimeUtc], #FirstSequence = [Sequence] FROM [ELMAH_Error]
WHERE [Application] = #Application ORDER BY [TimeUtc] DESC, [Sequence] DESC
END
ELSE
BEGIN
SET #PageSize = 0
END
SET ROWCOUNT #PageSize
SELECT
errorId = [ErrorId],
application = [Application],
host = [Host],
type = [Type],
source = [Source],
message = [Message],
[user] = [User],
statusCode = [StatusCode],
time = CONVERT(VARCHAR(50), [TimeUtc], 126) + ''Z''
FROM [ELMAH_Error] error WHERE [Application] = #Application AND [TimeUtc] <= #FirstTimeUTC
AND [Sequence] <= #FirstSequence ORDER BY [TimeUtc] DESC, [Sequence] DESC FOR XML AUTO')");
Sql(#"EXEC('CREATE PROCEDURE [dbo].[ELMAH_LogError] (#ErrorId UNIQUEIDENTIFIER, #Application NVARCHAR(60), #Host NVARCHAR(30),
#Type NVARCHAR(100), #Source NVARCHAR(60), #Message NVARCHAR(500), #User NVARCHAR(50), #AllXml NTEXT, #StatusCode INT,
#TimeUtc DATETIME) AS
SET NOCOUNT ON
INSERT INTO [ELMAH_Error] ([ErrorId], [Application], [Host], [Type], [Source], [Message], [User], [AllXml], [StatusCode], [TimeUtc])
VALUES (#ErrorId, #Application, #Host, #Type, #Source, #Message, #User, #AllXml, #StatusCode, #TimeUtc)')");
}
public override void Down()
{
Sql("EXEC('DROP PROCEDURE [ELMAH_GetErrorXml]')");
Sql("EXEC('DROP PROCEDURE [ELMAH_GetErrorsXml]')");
Sql("EXEC('DROP PROCEDURE [ELMAH_LogError]')");
Sql("Drop table ELMAH_Error");
}
Now when you will execute Update-Database command in "Package Manager Console", ELMAH_Error table and associated procedures will be created in the database.
Elmah source has been moved to GitHub. The current file for SQL Server is located in the SqlErrorLog repo under the Elmah organization.
SqlErrorLog: /src/SQLServer.sql
Other database scripts can be found by searching errorlog under the Elmah GitHub organization. e.g. https://github.com/elmah?q=errorlog
Related
I have a json string which is the result of Get Metadata activity in data factory in the following format: {"structure": [{"name": "Id","type": "String"},{"name": "IsDeleted","type": "Boolean"},{"name": "RowVersion","type": "Byte[]"}, {"name": "ModelId","type": "String"}]
This json is showing the schema of parquet file. I pass this json along with the parquet filename and uctnow() to a stored procedure to create a table of schema for that file with the following code
CREATE OR ALTER PROCEDURE [CreateExternalTables] (
#schema NVARCHAR (MAX), #tableName NVARCHAR(MAX), #ExecTime NVARCHAR(MAX)
) AS
BEGIN
IF OBJECT_ID('tempdb..#tables_to_create', 'U') IS NOT NULL
DROP TABLE #tables_to_create
CREATE TABLE #tables_to_create (
tableName NVARCHAR (MAX),
fieldOrder NVARCHAR (MAX),
fieldName NVARCHAR (MAX),
fieldType NVARCHAR (MAX),
translatedType NVARCHAR (MAX),
executeTime NVARCHAR (MAX)
)
BEGIN
WITH Fields (fieldOrder, fieldName, fieldType) AS (
SELECT
[key] AS fieldOrder,
JSON_VALUE([value], '$.name') AS fieldName,
JSON_VALUE([value], '$.type') AS fieldType
FROM
OPENJSON(#schema)
)
INSERT INTO
#tables_to_create(
tableName,
fieldOrder,
fieldName,
fieldType,
translatedType,
executeTime
)
SELECT
#tableName,
fieldOrder,
fieldName,
fieldType,
CASE
WHEN fieldType = 'Single' THEN 'real'
WHEN fieldType = 'Boolean' THEN 'bit'
WHEN fieldType = 'Double' THEN 'float'
WHEN fieldType = 'Int64' THEN 'bigint'
ELSE NULL
END AS translatedType,
#ExecTime
FROM
Fields
END
END;
The overall setup is like below:
But I receive the following error which I'm not sure why:
What I would like to do is to create this temo table in stored procedure in order to create external tables in a automatic way.
To be precise I'm following this link to do it:
create-external-dataset
Any help is highly appreciated.
UPDATE
After solving the first problem with #wBob 's help I follow the rest of the link to create the external tables with the following which I inserted into my stored procedure:
FROM
Fields
END
Declare #sqlCommand nvarchar(max);
Declare #folderPath nvarchar(max);
SET
#sqlCommand = 'IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[dbo].[' + #tableName + ']'') AND type in (N''U''))
CREATE EXTERNAL TABLE [dbo].[' + #tableName + '] ('
WHILE((SELECT COUNT(*) FROM #tables_to_create) > 0)
BEGIN
DECLARE #key int
SELECT
#key = MIN(fieldOrder)
FROM
#tables_to_create
WHERE
executeTime = #ExecTime
DECLARE #fieldName VARCHAR(50)
DECLARE #translatedType VARCHAR(50)
SELECT
#fieldName = fieldName,
#translatedType = translatedType
FROM
#tables_to_create
WHERE
fieldOrder = #key
AND executeTime = #ExecTime
SET
#sqlCommand = #sqlCommand + '
[' + #fieldName + '] [' + #translatedType + '] NULL'
DELETE FROM
#tables_to_create
WHERE
fieldOrder = #key
AND executeTime = #ExecTime
IF((SELECT COUNT(*) FROM #tables_to_create WHERE executeTime = #ExecTime) > 0)
SET
#sqlCommand = #sqlCommand + ', '
END
SET
#sqlCommand = #sqlCommand + '
)
WITH
(
LOCATION = ''/' + /main/json/ + ''',
DATA_SOURCE = DataLakeStaged,
FILE_FORMAT = StagedParquet
)'
EXEC(#sqlCommand)
END;
However I receive the following error:
As per the error message, queries are not supported in the conditions of WHILE statement in Azure Synapse Analytics. Dedicated SQL pools are MPP systems that have some slight differences from box-product SQL Server and Azure SQL DB and more generally, loops are a pattern that don't translate that well. You should consider creating a stored procedure that does not loop and leave any looping required to the For Each activity in Azure Data Factory (ADF) / Synapse Pipelines which can loop in parallel.
If you do require a loop, there are multiple examples of doing loops in dedicated SQL pools online, but there is a good example in the official documentation, reproduced here in the event the link moves:
-- First, create a temporary table containing a unique row number used to identify the individual statements:
CREATE TABLE #tbl
WITH
( DISTRIBUTION = ROUND_ROBIN
)
AS
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS Sequence
, [name]
, 'UPDATE STATISTICS '+QUOTENAME([name]) AS sql_code
FROM sys.tables
;
-- Second, initialize the variables required to perform the loop:
DECLARE #nbr_statements INT = (SELECT COUNT(*) FROM #tbl)
, #i INT = 1
;
-- Now loop over statements executing them one at a time:
WHILE #i <= #nbr_statements
BEGIN
DECLARE #sql_code NVARCHAR(4000) = (SELECT sql_code FROM #tbl WHERE Sequence = #i);
EXEC sp_executesql #sql_code;
SET #i +=1;
END
I can't get this simple query right. I need to join my adresses table to my annonces table.
I supose this should be farly strait forward but I simply can't get it to work.
I firstly made my adresse table object like this
class AdressesTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('Annonces', [
'foreignKey' => 'annonceId',
'joinType' => 'INNER',
]);
}
}
Then in my annonces controller I tryed to join the adresses like this
public function view($id = null)
{
if (!$id) {
throw new NotFoundException(__('Annonce invalide!'));
}
$query = $this->Annonces->find('all', ['contain' => ['Adresses']])->where(['id' => $id]);
$annonce = $query->firstOrFail();
$this->set(compact('annonce'));
}
But then I got this error :
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Adresses.annonce_id' in 'where clause'
Witch I don't understand why I got it since I have defined my foreign key in the AdressesTable class.
The query I would like to have at the end would look like this
SELECT *
FROM annonces
INNER JOIN adresses ON adresses.annonceId = annonces.id
WHERE annonces.id = #param
*PS. I know it wont be select * but rather select [all my column]*
EDIT : My table schema are as following
CREATE TABLE annonces(
id INT NOT NULL AUTO_INCREMENT, #PK
startDate DATE NOT NULL,
endDate DATE NOT NULL,
title VARCHAR(128) NOT NULL,
descript TEXT NOT NULL,
infoSupplementaire TEXT NULL,
premium BIT NOT NULL,
clientId INT NOT NULL, #FK
categorieId INT NOT NULL, #FK
CONSTRAINT pk_annonces_id PRIMARY KEY (id),
CONSTRAINT fk_annonces_clientId FOREIGN KEY (clientId) REFERENCES clients(id),
CONSTRAINT fk_annonces_categorieId FOREIGN KEY (categorieId) REFERENCES categories(id)
);
CREATE TABLE adresses(
id INT NOT NULL AUTO_INCREMENT, #PK
latitude DECIMAL(11,7),
longitude DECIMAL(11,7),
adresse VARCHAR(512),
annonceId INT NOT NULL, #FK
CONSTRAINT pk_adresses_id PRIMARY KEY (id),
CONSTRAINT fk_adresses_annonceId FOREIGN KEY (annonceId) REFERENCES annonces(id)
)
I solved my problem by renaming my column folowing cakephp convention and using any of the code from this answer
You can try
$query = $this->Annonces->find('all', ['contain' => ['Adresses']])->where(['Annonces.id' => $id]);
$annonce = $query->firstOrFail();
OR
public function view($id = null)
{
if (!$id) {
throw new NotFoundException(__('Annonce invalide!'));
}
$annonceEntity = $this->Annonces->get($id);
$query = $this->Annonces->find('all', ['contain' => ['Adresses']])->where(['Annonces.id' => $annonceEntity->id]);
$annonce = $query->firstOrFail();
$this->set(compact('annonce'));
}
I am trying to get this stored procedure to work. I have been working for a month straight, was up till 3 last night, and am approaching burnout. I really want to get this to work as we have an ad campaign that we spent hundreds on sending traffic to.
USE [redhotkitties2005db]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[proc_rhkprod_lock_items_for_paypal]
#cfuseridid bigint
,#transaction_guid uniqueidentifier = NULL
AS
BEGIN
SET NOCOUNT ON;
declare #tblcartID bigint
,#cfuserid bigint
,#tblproductsid bigint
,#quantity bigint
,#localInventoryID varchar(100)
,#taxologykey bigint
,#name varchar(1000)
,#shortDescription varchar(8000)
,#productDescription varchar(8000)
,#UorLorUL varchar(2)
,#unitPrice money
,#shippingWeight numeric(6, 2)
,#overSize tinyint
,#smallPic1 nvarchar(100)
,#largePic1 nvarchar(100)
,#smallPic2 nvarchar(100)
,#largePic2 nvarchar(100)
,#smallPic3 nvarchar(100)
,#largePic3 nvarchar(100)
SET #transaction_guid = coalesce(#transaction_guid,newid())
declare c1 cursor forward_only for
select rhkProd_tblCart.tablePK AS tblcartID
,rhkProd_tblProducts.productID as tblproductsid
,rhkProd_tblCart.quantity
,rhkProd_tblProducts.localInventoryID
,rhkProd_tblProducts.name
,rhkProd_tblProducts.taxologyKey
,rhkProd_tblProducts.shortDescription
,rhkProd_tblProducts.productDescription
,rhkProd_tblProducts.UorLorUL
,rhkProd_tblProducts.unitPrice
,rhkProd_tblProducts.shippingWeight
,rhkProd_tblProducts.overSize
,rhkProd_tblProducts.smallPic1
,rhkProd_tblProducts.largePic1
,rhkProd_tblProducts.smallPic2
,rhkProd_tblProducts.largePic2
,rhkProd_tblProducts.smallPic3
,rhkProd_tblProducts.largePic3
from rhkProd_tblCart
INNER JOIN rhkProd_tblProducts
on rhkProd_tblCart.tblProductsFK = rhkProd_tblProducts.productID
where rhkProd_tblCart = #cfuserid
open c1
fetch next
from c1
into #tblcartID
,#cfuserid
,#tblproductsid
,#quantity
,#localinventoryID
,#name
,#taxologykey
,#shortdescription
,#productdescription
,#UorLorUL
,#unitprice
,#shippingweight
,#oversize
,#smallpic1
,#largepic1
,#smallpic2
,#largepic2
,#smallpic3
,#largepic3
begin
while ##fetch_status = 0
insert into rhkprod_tblpaypallock (
,[cfuserid]
,[transaction_guid]
,[timestamp]
,[tblproductsFK]
,[quantity]
,[localInventoryID]
,[name]
,[taxologykey]
,[shortdescription]
,[productdescription]
,[uorlorul]
,[unitprice]
,[shippingweight]
,[oversize]
,[smallpic1]
,[largepic1]
,[smallpic2]
,[largepic2]
,[smallpic3]
,[largepic3]
)
values (
,#cfuserid
,#transaction_guid
,getdate()
,#tblproductsid
,#quantity
,#localinventoryID
,#name
,#taxologykey
,#shortdescription
,#productdescription
,#UorLorUL
,#unitprice
,#shippingweight
,#oversize
,#smallpic1
,#largepic1
,#smallpic2
,#largepic2
,#smallpic3
,#largepic3
)
update rhkprod_tblproducts
set quantity = quantity - #quantity
where productid = #tblproductsid
and UorLorUL in ('U','L')
fetch next
from c1
into #tblcartID
,#cfuserid
,#tblproductsid
,#quantity
,#localinventoryID
,#name
,#taxologykey
,#shortdescription
,#productdescription
,#UorLorUL
,#unitprice
,#shippingweight
,#oversize
,#smallpic1
,#largepic1
,#smallpic2
,#largepic2
,#smallpic3
,#largepic3
close c1
deallocate c1
end
END
Your INSERT statement has a stray comma at the start:
insert into rhkprod_tblpaypallock (
,[cfuserid]
Should be
insert into rhkprod_tblpaypallock (
[cfuserid]
Your VALUES clause also has a stray comma:
values (
,#cfuserid
Should be
values (
#cfuserid
I woud like to inquire if my Linq solution below is a good solution or if there is a better way. I am new to using Linq, and am most familiar with MySQL. So I've been converting one of my past projects from PHP to .NET MVC and am trying to learn Linq. I would like to find out if there is a better solution than the one I came up with.
I have the following table structures:
CREATE TABLE maplocations (
ID int NOT NULL AUTO_INCREMENT,
name varchar(35) NOT NULL,
Lat double NOT NULL,
Lng double NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY name (name)
);
CREATE TABLE reservations (
ID INT NOT NULL AUTO_INCREMENT,
loc_ID INT NOT NULL,
resDate DATE NOT NULL,
user_ID INT NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY one_per (loc_ID, resDate),
FOREIGN KEY (user_ID) REFERENCES Users (ID),
FOREIGN KEY (loc_ID) REFERENCES MapLocations (ID)
);
CREATE TABLE Users (
ID INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
email VARCHAR(50) NOT NULL,
pass VARCHAR(128) NOT NULL,
salt VARCHAR(5) NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY unique_names (name),
UNIQUE KEY unique_email (email)
);
In MySQL, I use the following query to get the ealiest reservation at each maplocation with a non null date for any locations that don't have a reservation.
SELECT locs.*, if(res.resDate,res.resDate,'0001-01-01') as resDate, res.Name as User
FROM MapLocations locs
LEFT JOIN (
SELECT loc_ID, resDate, Name
FROM Reservations, Users
WHERE resDate >= Date(Now())
AND user_ID = Users.ID
ORDER BY resDate
) res on locs.ID = res.loc_ID
group by locs.ID
ORDER BY locs.Name;
In Linq, with Visual studio automatically creating much of the structure after connecting to the database, I have come up with the following equivalent to that SQL Query
var resList = (from res in Reservations
where res.ResDate >= DateTime.Today
select res);
var locAndRes =
(from loc in Maplocations
join res in resList on loc.ID equals res.Loc_ID into join1
from res2 in join1.DefaultIfEmpty()
join usr in Users on res2.User_ID equals usr.ID into join2
from usr2 in join2.DefaultIfEmpty()
orderby loc.ID,res2.ResDate
select new {
ID = (int)loc.ID,
Name = (string)loc.Name,
Lat = (double)loc.Lat,
Lng = (double)loc.Lng,
resDate = res2 != null ?(DateTime)res2.ResDate : DateTime.MinValue,
user = usr2 != null ? usr2.Name : null
}).GroupBy(a => a.ID).Select(b => b.FirstOrDefault());
So, I'm wondering is there a better way to perform this query?
Are these equivalent?
Are there any good practices I should be following?
Also, one more question, I'm having trouble getting this from the var to a List. doing something like this doesn't work
List<locAndResModel> locList = locAndRes.AsQueryable().ToList<locAndResModel>();
In the above snippet locAndResModel is just a class which has variables to match the int, string, double double, DateTime, string results of the query. Is there an easy way to get a list without having to do a foreach and passing the results to a constructor override? Or should I just add it to ViewData and return the View?
You'll want to take advantage of the automatic joins performed by the Entity Framework. Give this a try and let me know if it does what you want:
var locAndRes = from maplocation in MapLocations
let earliestReservationDate = maplocation.Reservations.Min(res => res.resDate)
let earliestReservation = (from reservation in mapLocation.Reservations
where reservation.resDate == earliestReservationDate && reservation.resDate >= DateTime.Today
select reservation).FirstOrDefault()
select new locAndResModel( maplocation.ID, maplocation.name, maplocation.Lat, maplocation.Lng, earliestReservation != null ? earliestReservation.resDate : DateTime.MinValue, earliestReservation != null ?earliestReservation.User.name : null)
Here goes, second post, first didn't go to well....
I am calling an SP from a Gridview in ASP. I pass in a table name as a variable along with some other variables. I need to UPDATE my original table that the Gridview attaches to but also build a Datalist, I have used a Fetch and got it working fine. Cycle through those records and INSERT data into third table. I was told (in first post) I need to build the SQL string first then execute it. when I write it that way the second part of the insert does not work.
Here is the code in its sliced up form because of efforts to find a succesfull structure....
#currTable varchar(100),
#ID int,
#short_Text varchar(250),
#brief_Descrip varchar(250) = Null,
#needsTranslation varchar(10) = Null,
#prev_LangString varchar(250) = Null,
#lang_String varchar(250) = Null,
#original_lang_String varchar(250) = Null,
#StringID_from_Master varchar(250),
#GUID varchar(250) = Null
/*
*/
AS
SET NOCOUNT ON;
DECLARE #userTable AS VARCHAR(200);
SET #userTable = #currTable
DECLARE #submitDate1 DATETIME;
SET #submitDate1 = GETDATE()
SET #prev_LangString = #original_lang_String
SET #needsTranslation = 'false'
DECLARE #sql varchar(max)
-- Establish update to the language tabel of user and prepare to search DB for all strings that will need to be updated.
BEGIN
-- DECLARE #sql nvarchar(4000)
SELECT #sql = ' UPDATE ' + #currTable +
' SET [lang_String] = ' + #lang_String +
' WHERE (ID = ' + #ID + ' ';
EXEC sp_executesql #sql, N'#ID nvarchar(10)', #ID
-- UPDATE #userTable
-- SET [lang_String] = #lang_String, [date_Changed] = #submitDate1, [prev_LangString] = #prev_LangString, [needsTranslation] = #needsTranslation, [brief_Descrip] = #brief_Descrip
-- WHERE (ID = #ID)
END
BEGIN
DECLARE usedIN_DBScursor CURSOR
FOR
SELECT tblUniquetblStringsMaster_ID, Database_Name, dbKeyID_ofStringName
FROM tblDBUsage
WHERE (tblUniquetblStringsMaster_ID = #StringID_from_Master );
-- Declare the variables to store the values returned by FETCH.
DECLARE #tblUniquetblStringsMaster_ID AS INT;
DECLARE #dbKEYID as INT;
DECLARE #dbName as varchar(100);
OPEN usedIN_DBScursor;
-- Perform the first fetch and store the values in variables.
-- Note: The variables are in the same order as the columns
-- in the SELECT statement.
FETCH NEXT FROM usedIN_DBScursor
INTO #tblUniquetblStringsMaster_ID, #dbName, #dbKEYID;
-- Check ##FETCH_STATUS to see if there are any more rows to fetch.
WHILE ##FETCH_STATUS = 0
BEGIN
-- Update pending strings table with translation.
BEGIN
INSERT INTO tblPendingDBUpdates
(stringMasterID, databaseName, databaseStringID, englishText, foreignLangText, submitDate, GUID)
VALUES (#StringID_from_Master, #dbName, #dbKEYID, #short_Text, #lang_String, #submitDate1, #GUID);
END
-- SET #sql = ''
-- This is executed as long as the previous fetch succeeds.
FETCH NEXT FROM usedIN_DBScursor
INTO #tblUniquetblStringsMaster_ID, #dbName, #dbKEYID;
END
CLOSE usedIN_DBScursor;
DEALLOCATE usedIN_DBScursor;
END
RETURN
It seems that your procedure could be re-written as follows:
ALTER PROCEDURE dbo.procedure_name
#currTable varchar(100),
#ID int,
#short_Text varchar(250),
#brief_Descrip varchar(250) = Null,
#needsTranslation varchar(10) = Null,
#prev_LangString varchar(250) = Null,
#lang_String varchar(250) = Null,
#original_lang_String varchar(250) = Null,
#StringID_from_Master varchar(250),
#GUID varchar(250) = Null
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sql NVARCHAR(MAX);
SELECT #sql = N' UPDATE ' + QUOTENAME(#currTable) + ' SET [lang_String] = '''
+ REPLACE(#lang_String,'''','''''') + ''' WHERE ID = ' + RTRIM(#ID) + ';';
EXEC sp_executesql #sql;
INSERT tblPendingDBUpdates
(
stringMasterID,
databaseName,
databaseStringID,
englishText,
foreignLangText,
submitDate,
[GUID]
)
SELECT
#StringID_from_Master,
Database_Name,
dbKeyID_ofStringName,
#short_Text,
#lang_String,
#submitDate1,
#GUID
FROM
tblDBUsage
WHERE tblUniquetblStringsMaster_ID = #StringID_from_Master;
END
GO
However, I am not sure why you need a cursor in your original version, or what you mean by "does not work." Can you explain?
I don't quite understand your problem, but I see one thing that's obviously wrong: In the SQL you're building a string literal is missing its quotes and there's a missing parenthesis. The SQL you're generating would look like this:
UPDATE table_name SET [lang_String] = lang_string WHERE (ID = 123
So it should be:
DECLARE #sql nvarchar(4000)
SELECT #sql = 'UPDATE ' + #currTable + ' SET [lang_String] = ''' + #lang_String + ''' WHERE ID = ' + #ID
Which generates this SQL:
UPDATE table_name SET [lang_String] = 'lang_string' WHERE ID = 123