Having issues with UPDATE command - sql

Using this SP I keep getting an error on the UPDATE statement indicating that I have conversion problem or something. But ID is an integer in all of my tables....
Conversion failed when converting the varchar value 'UPDATE tblLangenUS SET [lang_String] = ' - asdfgsdfg', [prev_LangString] = ' ', [needsTranslation] = 'false' WHERE [ID] = '' to data type int.
#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
SET #sql = 'UPDATE ' + #currTable + ' SET [lang_String] = ''' + #lang_String + ''', [prev_LangString] = ''' + #prev_LangString + ''', [needsTranslation] = ''' + #needsTranslation + ''' WHERE [ID] = ''' + #ID + '''; '
EXEC #sql
#sql = ''
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

If the ID is an int, you must CAST it to an nvarchar
SET #sql = 'UPDATE ' + #currTable + ' SET [lang_String] = ''' + #lang_String + ''', [prev_LangString] = ''' + #prev_LangString + ''', [needsTranslation] = ''' + #needsTranslation + ''' WHERE [ID] = ''' + CAST(#ID as nvarchar(10)) + '''; '
Otherwise, you are trying to add a string and an integer together, which won't work.
Notice this part:
' WHERE [ID] = ''' + CAST(#ID as nvarchar(10)) + '''
I think you must also change your EXEC syntax to:
EXEC(#sql)

Related

Run a dynamic SQL query from a stored procedure to populate a GridView

I have a dynamic query that adds WHERE clauses according to the parameters received:
DECLARE #p1 varchar(max);
DECLARE #p2 varchar(max);
DECLARE #p3 varchar(max);
DECLARE #p4 varchar(max);
DECLARE #p5 varchar(max);
DECLARE #p6 varchar(max);
DECLARE #p7 varchar(max);
DECLARE #p8 varchar(max);
DECLARE #p9 varchar(max);
DECLARE #p10 varchar(max);
DECLARE #p11 varchar(max);
DECLARE #p12 varchar(max);
SET #p9 = 'Acta'
DECLARE #SQL varchar(max);
SET #SQL =
'SELECT
COUNT(*) AS [regs]
FROM [dbo].[DP_Fichas] [F]
WHERE 1 = 1';
IF(#p1 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[ID] = ''' + #p1 + ''''
END;
IF(#p2 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[Titulo] LIKE ''%' + #p2 + '%'''
END;
IF(#p3 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[Texto] = ''' + #p3 + ''''
END;
IF(#p4 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[Fecha] = ''' + #p4 + ' 00:00:00.0000000'''
END;
IF(#p5 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[Constitucionailidad] = ''' + #p5 + ''''
END;
IF(#p6 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[Comentarios] = ''' + #p6 + ''''
END;
IF(#p7 IS NOT NULL)
BEGIN
DECLARE #idfuente varchar(max)
SET #idfuente =
(
SELECT
[X1].[ID]
FROM [dbo].[DP_Fuentes] [X1]
WHERE
([X1].[Nombre] = #p7)
)
SET #SQL = #SQL + '
AND [F].[IdFuente] = ''' + #idfuente + ''''
END;
IF(#p8 IS NOT NULL)
BEGIN
DECLARE #idvigencia varchar(max)
SET #idvigencia =
(
SELECT
[X1].[ID]
FROM [dbo].[DP_Vigencia] [X1]
WHERE
([X1].[Nombre] = #p8)
)
SET #SQL = #SQL + '
AND [F].[IdVigencia] = ''' + #idvigencia + ''''
END;
IF(#p9 IS NOT NULL)
BEGIN
DECLARE #idtipo varchar(max)
SET #idtipo =
(
SELECT
[X1].[ID]
FROM [dbo].[DP_TipoFicha] [X1]
WHERE
([X1].[Nombre] = #p9)
)
SET #SQL = #SQL + '
AND [F].[IdIdentificacion] = ''' + #idtipo + ''''
END;
IF(#p10 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[NormaNumero] = ''' + #p10 + ''''
END;
IF(#p11 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[Publicacion] = ''' + #p11 + ''''
END;
IF(#p12 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[TemaResumen] = ''' + #p12 + ''''
END;
EXEC(#SQL);
In this example, only the #p9 parameter has a value, so the returned SQL command will be:
SELECT COUNT(*) AS [regs]
FROM [dbo].[DP_Fichas] [F]
WHERE 1 = 1
AND [F].[IdIdentificacion] = '2'
This is working just fine when I execute the query, but when I save it to a stored procedure, it comes back empty.
This is the code for the stored procedure:
CREATE PROCEDURE [dbo].[SEL_DP_Fichas_Buscar_Algoritmo_Contar]
(
#p1 varchar(max),
#p2 varchar(max),
#p3 varchar(max),
#p4 varchar(max),
#p5 varchar(max),
#p6 varchar(max),
#p7 varchar(max),
#p8 varchar(max),
#p9 varchar(max),
#p10 varchar(max),
#p11 varchar(max),
#p12 varchar(max)
)
AS
BEGIN
DECLARE #p1f varchar(max) = #p1;
DECLARE #p2f varchar(max) = #p2;
DECLARE #p3f varchar(max) = #p3;
DECLARE #p4f varchar(max) = #p4;
DECLARE #p5f varchar(max) = #p5;
DECLARE #p6f varchar(max) = #p6;
DECLARE #p7f varchar(max) = #p7;
DECLARE #p8f varchar(max) = #p8;
DECLARE #p9f varchar(max) = #p9;
DECLARE #p10f varchar(max) = #p10;
DECLARE #p11f varchar(max) = #p11;
DECLARE #p12f varchar(max) = #p12;
DECLARE #SQL varchar(max);
SET #SQL =
'SELECT
COUNT(*)
FROM [dbo].[DP_Fichas] [F]
WHERE 1 = 1'
IF(#p1 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[ID] = ''' + #p1 + ''''
END;
IF(#p2 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[Titulo] LIKE ''%' + #p2 + '%'''
END;
IF(#p3 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[Texto] = ''' + #p3 + ''''
END;
IF(#p4 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[Fecha] = ''' + #p4 + ' 00:00:00.0000000'''
END;
IF(#p5 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[Constitucionailidad] = ''' + #p5 + ''''
END;
IF(#p6 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[Comentarios] = ''' + #p6 + ''''
END;
IF(#p7 IS NOT NULL)
BEGIN
DECLARE #idfuente varchar(max)
SET #idfuente =
(
SELECT
[X1].[ID]
FROM [dbo].[DP_Fuentes] [X1]
WHERE
([X1].[Nombre] = #p7)
)
SET #SQL = #SQL + '
AND [F].[IdFuente] = ''' + #idfuente + ''''
END;
IF(#p8 IS NOT NULL)
BEGIN
DECLARE #idvigencia varchar(max)
SET #idvigencia =
(
SELECT
[X1].[ID]
FROM [dbo].[DP_Vigencia] [X1]
WHERE
([X1].[Nombre] = #p8)
)
SET #SQL = #SQL + '
AND [F].[IdVigencia] = ''' + #idvigencia + ''''
END;
IF(#p9 IS NOT NULL)
BEGIN
DECLARE #idtipo varchar(max)
SET #idtipo =
(
SELECT
[X1].[ID]
FROM [dbo].[DP_TipoFicha] [X1]
WHERE
([X1].[Nombre] = #p9)
)
SET #SQL = #SQL + '
AND [F].[IdIdentificacion] = ''' + #idtipo + ''''
END;
IF(#p10 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[NormaNumero] = ''' + #p10 + ''''
END;
IF(#p11 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[Publicacion] = ''' + #p11 + ''''
END;
IF(#p12 IS NOT NULL)
BEGIN
SET #SQL = #SQL + '
AND [F].[TemaResumen] = ''' + #p12 + ''''
END;
EXECUTE (#SQL);
END
GO
Whenever I run the stored procedure:
EXEC [dbo].[SEL_DP_Fichas_Buscar_Algoritmo_Contar]
#p1 = '',
#p2 = '',
#p3 = '',
#p4 = '',
#p5 = '',
#p6 = '',
#p7 = '',
#p8 = '',
#p9 = 'Actas',
#p10 = '',
#p11 = '',
#p12 = '';
I should get 142 as a count result, but I'm getting:
Commands completed successfully.
Completion time: 2021-06-15T16:36:31.1131407-05:00
I need this stored procedure to fill up a GridView:
string spQuerySel0 = "SEL_DP_Fichas_Buscar_Algoritmo";
DataSet dsFlt1;
SqlConnection conFlt1;
SqlDataAdapter daFlt1;
conFlt1 = new SqlConnection(enchufe);
daFlt1 = new SqlDataAdapter(spQuerySel0, conFlt1);
daFlt1.SelectCommand.CommandType = CommandType.StoredProcedure;
daFlt1.SelectCommand.Parameters.AddWithValue("#p1", p1);
daFlt1.SelectCommand.Parameters.AddWithValue("#p2", p2);
daFlt1.SelectCommand.Parameters.AddWithValue("#p3", p3);
daFlt1.SelectCommand.Parameters.AddWithValue("#p4", p4);
daFlt1.SelectCommand.Parameters.AddWithValue("#p5", p5);
daFlt1.SelectCommand.Parameters.AddWithValue("#p6", p6);
daFlt1.SelectCommand.Parameters.AddWithValue("#p7", p7);
daFlt1.SelectCommand.Parameters.AddWithValue("#p8", p8);
daFlt1.SelectCommand.Parameters.AddWithValue("#p9", p9);
daFlt1.SelectCommand.Parameters.AddWithValue("#p10", p10);
daFlt1.SelectCommand.Parameters.AddWithValue("#p11", p11);
daFlt1.SelectCommand.Parameters.AddWithValue("#p12", p12);
dsFlt1 = new DataSet();
daFlt1.Fill(dsFlt1, spQuerySel0);
gvFichasRes.DataSource = dsFlt1.Tables[spQuerySel0].DefaultView;
gvFichasRes.DataBind();
daFlt1.Dispose();
conFlt1.Close();
But I'm getting a null exception, I guess that is because the stored procedure is returning nothing.
I've also tried to add OUTPUT to the query, but It'll break to a "Not found procedure" error.
What can I do here?
This type of query is known as a Kitchen-Sink query.
You have a number of issues with your current code:
#SQL should be declared as nvarchar(max)
You should parameterize the dynamic statement, in other words: the parameters should be pushed through via sp_executesql
The same applies to the subqueries, they can be run in the dynamic part
The parameter types should match the columns they are compared against, which in turn should be fitting for the data in them. I've made a guess at suitable types.
It's unclear what you hoped to achieve with the extra DECLARE #p1f statements, perhaps to avoid parameter sniffing, but that can be avoided with OPTION(OPTIMIZE FOR UNKNOWN), and in any case doing this dynamically means you probably should use parameter sniffing
In the C# side, you should dispose all SQL objects with using blocks
You should also avoid AddWithValue, specify the parameter types explicitly.
So your final procedure would look something like this:
CREATE PROCEDURE [dbo].[SEL_DP_Fichas_Buscar_Algoritmo_Contar]
(
#p1 int,
#p2 varchar(200),
#p3 varchar(200),
#p4 date,
#p5 char(2),
#p6 varchar(200),
#p7 int,
#p8 int,
#p9 int,
#p10 varchar(200),
#p11 varchar(200),
#p12 varchar(200)
)
AS
DECLARE #SQL nvarchar(max) =
N'
SELECT
COUNT(*)
FROM [dbo].[DP_Fichas] [F]
WHERE 1 = 1'
;
IF(#p1 IS NOT NULL)
SET #SQL += N'
AND [F].[ID] = #p1';
IF(#p2 IS NOT NULL)
SET #SQL += N'
AND [F].[Titulo] LIKE ''%'' + #p2 + ''%''';
IF(#p3 IS NOT NULL)
SET #SQL += N'
AND [F].[Texto] = #p3';
IF(#p4 IS NOT NULL)
SET #SQL += N '
AND [F].[Fecha] = #p4';
IF(#p5 IS NOT NULL)
SET #SQL += N'
AND [F].[Constitucionailidad] = #p5';
IF(#p6 IS NOT NULL)
SET #SQL += N'
AND [F].[Comentarios] = #p6';
IF(#p7 IS NOT NULL)
SET #SQL = #SQL + '
AND [F].[IdFuente] IN
(
SELECT
[X1].[ID]
FROM [dbo].[DP_Fuentes] [X1]
WHERE
([X1].[Nombre] = #p7)
)';
IF(#p8 IS NOT NULL)
SET #SQL = #SQL + '
AND [F].[IdVigencia] IN
(
SELECT
[X1].[ID]
FROM [dbo].[DP_Vigencia] [X1]
WHERE
([X1].[Nombre] = #p8)
)';
IF(#p9 IS NOT NULL)
SET #SQL = #SQL + '
AND [F].[IdIdentificacion] IN
(
SELECT
[X1].[ID]
FROM [dbo].[DP_TipoFicha] [X1]
WHERE
([X1].[Nombre] = #p9)
)';
IF(#p10 IS NOT NULL)
SET #SQL += N'
AND [F].[NormaNumero] = #p10';
IF(#p11 IS NOT NULL)
SET #SQL = #SQL + '
AND [F].[Publicacion] = #p11';
IF(#p12 IS NOT NULL)
SET #SQL += N'
AND [F].[TemaResumen] = #p12';
EXEC sp_executesql
#SQL,
N'#p1 int,
#p2 varchar(200),
#p3 varchar(200),
#p4 date,
#p5 char(2),
#p6 varchar(200),
#p7 int,
#p8 int,
#p9 int,
#p10 varchar(200),
#p11 varchar(200),
#p12 varchar(200)',
#p1 = #p1,
#p2 = #p2,
#p3 = #p3,
#p4 = #p4,
#p5 = #p5,
#p6 = #p6,
#p7 = #p7,
#p8 = #p8,
#p9 = #p9,
#p10 = #p10,
#p11 = #p11,
#p12 = #p12;
;
GO
I found the answer with the following lines of code:
DECLARE #statement NVARCHAR(4000);
SET #statement = #SQL;
EXECUTE sp_executesql #statement;
I added this to the end of the SP, solved the code issues suggested by SMor and everything worked.

Search a string in whole mysql database

I wrote this query for searching a string in whole database . Earlier it was working properly now it doesn't fetch full result at all . I don't get what is wrong with this query . Please help
QUERY
/*
- Search through tables to find specific text
- Written by Luis Chiriff (with help from SQL Server Central)
- luis.chiriff#gmail.com # 24/11/2008 # 11:54
*/
-- Variable Declaration
Declare #StringToFind VARCHAR(200), #Schema sysname, #Table sysname, #FullTable int, #NewMinID
int, #NewMaxID int,
#SQLCommand VARCHAR(8000), #BaseSQLCommand varchar(8000), #Where VARCHAR(8000), #CountCheck
varchar(8000) , #FieldTypes varchar(8000),
#cursor VARCHAR(8000), #columnName sysname, #SCn int, #SCm int
Declare #TableList table (Id int identity(1,1) not null, tablename varchar(250))
Declare #SQLCmds table (id int identity(1,1) not null, sqlcmd varchar(8000))
Declare #DataFoundInTables table (id int identity(1,1) not null, sqlcmd varchar(8000))
-- Settings
SET #StringToFind = 'abcdef'
SET NOCOUNT ON
SET #StringToFind = '%'+#StringToFind+'%'
-- Gathering Info
if ((select count(*) from sysobjects where name = 'tempcount') > 0)
drop table tempcount
create table tempcount (rowsfound int)
insert into tempcount select 0
-- This section here is to accomodate the user defined datatypes, if they have
-- a SQL Collation then they are assumed to have text in them.
SET #FieldTypes = ''
select #FieldTypes = #FieldTypes + '''' + rtrim(ltrim(name))+''',' from systypes where collation
is not null or xtype = 36
select #FieldTypes = left(#FieldTypes,(len(#FieldTypes)-1))
insert into #TableList (tablename)
select name from sysobjects
where xtype = 'U' and name not like 'dtproperties'
order by name
-- Start Processing Table List
select #NewMinID = min(id), #NewMaxID = max(id) from #TableList
while(#NewMinID <= #NewMaxID)
Begin
SELECT #Table = tablename, #Schema='dbo', #Where = '' from #TableList where id = #NewMinID
SET #SQLCommand = 'SELECT * FROM ' + #Table + ' WHERE'
-- removed ' + #Schema + '.
SET #cursor = 'DECLARE col_cursor CURSOR FOR SELECT COLUMN_NAME
FROM [' + DB_NAME() + '].INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ''' + #Schema + '''
AND TABLE_NAME = ''' + #Table + '''
AND DATA_TYPE IN ('+#FieldTypes+')'
--Original Check, however the above implements user defined data types --AND DATA_TYPE IN
(''char'',''nchar'',''ntext'',''nvarchar'',''text'',''varchar'')'
EXEC (#cursor)
SET #FullTable = 0
DELETE FROM #SQLCmds
OPEN col_cursor
FETCH NEXT FROM col_cursor INTO #columnName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #Where = #Where + ' [' + #columnName + '] LIKE ''' + #StringToFind + ''''
SET #Where = #Where + ' OR'
--PRINT #Table + '|'+ cast(len(isnull(#Where,''))+len(isnull(#SQLCommand,'')) as varchar(10))+'|'+#Where
if (len(isnull(#Where,''))+len(isnull(#SQLCommand,'')) > 3600)
Begin
SELECT #Where = substring(#Where,1,len(#Where)-3)
insert into #SQLCmds (sqlcmd) select #Where
SET #Where = ''
End
FETCH NEXT FROM col_cursor INTO #columnName
END
CLOSE col_cursor
DEALLOCATE col_cursor
if (#Where <> '')
Begin
SELECT #Where = substring(#Where,1,len(#Where)-3)
insert into #SQLCmds (sqlcmd)
select #Where --select #Table,count(*) from #SQLCmds
End
SET #BaseSQLCommand = #SQLCommand
select #SCn = min(id), #SCm = max(id) from #SQLCmds
while(#SCn <= #SCm)
Begin
select #Where = sqlcmd from #SQLCmds where ID = #SCn
if (#Where <> '')
Begin
SET #SQLCommand = #BaseSQLCommand + #Where
SELECT #CountCheck = 'update tempcount set rowsfound = (select count(*) '+ substring(#SQLCommand,10,len(#SQLCommand)) + ')'
EXEC (#CountCheck)
if ((select rowsfound from tempcount) > 0)
Begin
PRINT '--- ['+cast(#NewMinID as varchar(15))+'/'+cast(#NewMaxID as varchar(15))+'] '+#Table + ' ----------------------------------[FOUND!]'
--PRINT '--- [FOUND USING:] ' +#SQLCommand
insert into #DataFoundInTables (sqlcmd) select #SQLCommand
EXEC (#SQLCommand)
update tempcount set rowsfound = 0
End
else
Begin
PRINT '--- ['+cast(#NewMinID as varchar(15))+'/'+cast(#NewMaxID as varchar(15))+'] '+#Table
End
End
SET #SCn = #SCn + 1
End
set #NewMinID = #NewMinID + 1
end
if ((select count(*) from sysobjects where name = 'tempcount') > 0)
drop table tempcount
/*
This will now return all the sql commands you need to use
*/
select #NewMinID = min(id), #NewMaxID = max(id) from #DataFoundInTables
if (#NewMaxID > 0)
Begin
PRINT ' '
PRINT ' '
PRINT '-----------------------------------------'
PRINT '----------- TABLES WITH DATA ------------'
PRINT '-----------------------------------------'
PRINT ' '
PRINT 'We found ' + cast(#NewMaxID as varchar(10)) + ' table(s) with the string '+#StringToFind
PRINT ' '
while(#NewMinID <= #NewMaxID)
Begin
select #SQLCommand = sqlcmd from #DataFoundInTables where ID = #NewMinID
PRINT #SQLCommand
SET #NewMinID = #NewMinID + 1
End
PRINT ' '
PRINT '-----------------------------------------'
End
This query was working fine one month ago but now it doesn't fetch the results . Can anyone tell me what is wrong in this query .

Generate script with INSERT SELECT statements from T-SQL

I have two databases in SQL Server 2014 Express, since a few days ago I am unifying both databases in such a way that there is only one left.
When I have this new database I must pass it to Azure (I don't have any experience using this technology), however, I am doing tests on my local server, so far I have created the whole scheme but I must fill out all the tables to perform tests with my application.
There are 313 tables of which many have more than 200,000 records, my question is, what is the best way to populate the database?
Because at this moment I want to test my local machine, I could fill in the tables through Tasks> Generate Script> Advanced Options (Include only data) but this information will change the day when the migration to Azure is done, therefore I must Do the same process.
So, is it possible to create an INSERT SELECT script so that it does not include records one by one and is as dynamic as possible? For example, you would have to generate an INSERT INTO similar to this:
SET IDENTITY_INSERT [SchemaX].[TableA] ON ;
INSERT INTO [SchemaX].[TableA]
(
[id]
,[fieldA]
,[fieldB]
,[fieldC])
SELECT
[id]
,[fieldA]
,[fieldB]
,[fieldC]
FROM [server].[dbname].[SchemaX].[TableA]
SET IDENTITY_INSERT [SchemaX].[TableA] OFF ;
Some tables have IDENTITY enabled so you would have to recognize which tables are like this and use SET IDENTITY_INSERT when inserting. This way you would have to link the production server and insert the information into the local server.
If there are suggestions or recommendations about another way you are welcome
Has been answered before ...
/****** Object: StoredProcedure [dbo].[procUtils_GenerateInsertProc] Script Date: 03/20/2010 13:06:13 ******/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[procUtils_GenerateInsertProc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[procUtils_GenerateInsertProc]
GO
/****** Object: StoredProcedure [dbo].[procUtils_GenerateInsertProc] Script Date: 03/20/2010 13:06:13 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec procUtils_GenerateInsertProc 'Whatever'
--exec sp_HelpText procUtils_GenerateInsertProc
CREATE PROCEDURE [dbo].[procUtils_GenerateInsertProc]
#TableName [varchar](50)
WITH EXECUTE AS CALLER
AS
BEGIN -- proc start
SET NOCOUNT ON;
BEGIN TRY --begin try
--FIRST SEARCH THE TABLE WHICH HAD A "Feature" in its name
--SELECT NAME FROM SYS.TABLES WHERE NAME LIKE '%Feature%'
--SELECT column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Feature' --SELECT * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='Task'
--Decalre a variable to remember the position of the current delimiter
DECLARE #ProcName varchar(1000)
set #ProcName = '[dbo].[procGen_' + #TableName + '_Insert]'
DECLARE #CurrentDelimiterPositionVar INT
DECLARE #PkColumnName varchar(200)
--Decalre a variable to remember the number of rows in the table
DECLARE #Count INT
DECLARE #ColumnName varchar(300);
DECLARE #DataType varchar(50)
DECLARE #IsNullable bit
DECLARE #MaxLength INT
DECLARE #IsComputed BIT
set #IsComputed = 0
DECLARE #IsPrimaryKey BIT
set #IsPrimaryKey = 0
DECLARE #CODESTR VARCHAR(max)
--PRINT DROP PROCEDURE
set #CODESTR = ' '
--Declare the Table variable
DECLARE #ColumnNames TABLE
(
Number INT IDENTITY(1,1), --Auto incrementing Identity column
TableName varchar(300) , --the name of the table
ColumnName VARCHAR(300) , --The string value ,
DataType varchar(50) , --the datatype
IsNullable bit , --should we add =null in front
MaxLength INT , --VARCHAR(LENGHTi)
IsComputed bit , --whether or not this table is computed
IsPrimaryKey bit --whether or not this table is computed
)
--Populate the TABLE variable using some logic
-- SELECT * from INFORMATION_SCHEMA.COLUMNS
INSERT INTO #ColumnNames
(
TableName ,
ColumnName ,
DataType ,
IsNullable ,
MaxLength ,
IsComputed ,
IsPrimaryKey )
SELECT
TableName ,
ColumnName ,
DataType ,
IsNullable ,
MaxLength ,
IsComputed ,
IsPrimaryKey
from viewMeta_TableColumns
--debug where TableName = 'Whatever'
where TableName = #TableName
--SELECT column_name , Data_type , IsNullable , MaxLength
--from INFORMATION_SCHEMA.COLUMNS
--where TABLE_NAME=#TableName
--Initialize the looper variable
SET #CurrentDelimiterPositionVar = 1
--Determine the number of rows in the Table
SELECT #Count=max(Number) from #ColumnNames
--A variable to hold the currently selected value from the table
set #CODESTR = #CODESTR + 'IF OBJECT_ID(''' + #ProcName + ''') IS NOT NULL
BEGIN
DROP PROC ' + #ProcName + '
END
GO'
set #CODESTR = #CODESTR + '
/****** Object: StoredProcedure ' + #ProcName + '*/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE ' + #ProcName + '
#CurUserSessionId [int] ,
#CurPageTypeId [int] ,
#MsgOut [varchar](200) OUTPUT ,
#DebugMsgOut [varchar](200) OUTPUT,
#Ret [int] OUTPUT ,' + CHAR(13)
--#COLUMN_NAME [DATA_TYPE] (MAX_LENGTH) =NULL ,
WHILE #CurrentDelimiterPositionVar <= #Count --1st loop
BEGIN
--Load current value from the Table
SELECT #ColumnName = ColumnName FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar
SELECT #DataType = DataType FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar
SELECT #MaxLength = MaxLength FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar
set #IsNullable = ( select IsNullable FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar )
set #IsPrimaryKey = ( select IsPrimaryKey FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar )
if ( #DataType = 'timestamp' or #IsComputed = 1)
begin
set #CurrentDelimiterPositionVar = #CurrentDelimiterPositionVar + 1
continue
end
set #CODESTR = #CODESTR + '#' + #ColumnName + ' ['+ #DataType + '] '
--ADD THE (200)
IF #MaxLength IS NOT NULL
BEGIN --IF #MaxLength IS NOT NULL
--xml
if #DataType <> 'xml' and #DataType <> 'sql_variant' and
#DataType <> 'text' and #DataType <> 'ntext' and #DataType <> 'image' and
#DataType <> 'hierarchyid' and #DataType <> 'bit' and #DataType <> 'varbinary' and
#DataType <> 'int' and #DataType <> 'uniqueidentifier' and #DataType <> 'tinyint' and
#DataType <> 'timestamp' and #DataType <> 'uniqueidentifier' and #DataType <> 'smallint' and
#DataType <> 'bigint' and #DataType <> 'smallmoney' and #DataType <> 'money' and
#DataType <> 'real' and #DataType <> 'smalldatetime' and #DataType <> 'datetime'
begin --those with()
if #MaxLength <> -1
SET #CODESTR = #CODESTR + '(' + CONVERT(VARCHAR , #MaxLength ) + ')'
else
SET #CODESTR = #CODESTR + '(max)'
end --those with(200)
else
begin
SET #CODESTR = #CODESTR --DO NOTHING
end
END --IF #MaxLength IS NOT NULL
IF #IsNullable = 1
SET #CODESTR = + #CODESTR + ' = NULL '
if #IsPrimaryKey = 1
SET #CODESTR = #CODESTR + ' OUTPUT '
if #CurrentDelimiterPositionVar <> #Count
SET #CODESTR = #CODESTR + ','
--DEBUGGING
--set #CODESTR = #CODESTR + '#ColumnName - ' + #ColumnName
--set #CODESTR = #CODESTR + '#DataType - ' + #DataType
--set #CODESTR = #CODESTR + '#IsNullable - ' + #IsNullable
--set #CODESTR = #CODESTR + '#MaxLength - ' + CONVERT ( VARCHAR , #MaxLength )
set #CODESTR = #CODESTR + CHAR(13)
SET #CurrentDelimiterPositionVar = #CurrentDelimiterPositionVar + 1
END
SET #CODESTR = #CODESTR + '
WITH EXECUTE AS CALLER
AS
BEGIN -- proc start
SET NOCOUNT ON;
BEGIN TRY --begin try
--
set #Ret = 1 --assume false from the beginning
declare #MsgKey [nvarchar](max)
declare #MsgTxt [nvarchar](max)
exec procUtils_GetMsgTxtByKeyAndUserSessionId
#UserSessionId =2 ,
#MsgKey = ''MsgOkTheAddingOfItemIsOk'' ,
#MsgTxt = ''''
set #MsgOut = replace (#MsgTxt , ''{0}'' , ''' + #TableName + ''' )
declare #thisProcName varchar(300)
set #thisProcName= ( SELECT OBJECT_NAME(##PROCID))
'
SET #CurrentDelimiterPositionVar = 1 --START LOOP AGAIN
set #CODESTR = #CODESTR + '
--Action !!!
INSERT INTO [dbo].[' + #TableName + ']( ' + CHAR(13)
--Loop through until all row processing is done
WHILE #CurrentDelimiterPositionVar <= #Count --2nd loop
BEGIN
--Load current value from the Table
SELECT #ColumnName = ColumnName FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar
SELECT #DataType = DataType FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar
SELECT #MaxLength = MaxLength FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar
set #IsNullable = ( select IsNullable FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar )
set #IsPrimaryKey = ( select IsPrimaryKey FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar )
if #IsPrimaryKey = 1
begin -- the primary key
set #PkColumnName = #ColumnName
end --the primary key
if ( #DataType = 'timestamp' or #IsComputed = 1 or #IsPrimaryKey = 1 )
begin
set #CurrentDelimiterPositionVar = #CurrentDelimiterPositionVar + 1
continue
end
--select
if #CurrentDelimiterPositionVar <= #Count
BEGIN
set #CODESTR = #CODESTR + '[' + #ColumnName + ']' --null the codestring var
if #CurrentDelimiterPositionVar <> #Count
set #CODESTR = #CODESTR + ', --type of ' + #DataType + CHAR(13) --WITH COMMA
ELSE
set #CODESTR = #CODESTR + ' --type of ' + #DataType + CHAR(13) --NO COMMA
END -- IF SHOULD PRINT COLUMN
SET #CurrentDelimiterPositionVar = #CurrentDelimiterPositionVar + 1;
END --eof while 2
set #CODESTR = #CODESTR + ') VALUES ( '
--AND START ALL OVER AGAIN
SET #CurrentDelimiterPositionVar = 1
--Loop through until all row processing is done
WHILE #CurrentDelimiterPositionVar <= #Count --WHILE 3
BEGIN
--Load current value from the Table
SELECT #ColumnName = ColumnName FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar
SELECT #DataType = DataType FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar
SELECT #MaxLength = MaxLength FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar
set #IsNullable = ( select IsNullable FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar )
set #IsPrimaryKey = ( select IsPrimaryKey FROM #ColumnNames
WHERE Number = #CurrentDelimiterPositionVar )
if ( #DataType = 'timestamp' or #IsComputed = 1 or #IsPrimaryKey = 1)
begin
set #CurrentDelimiterPositionVar = #CurrentDelimiterPositionVar + 1
continue
end
set #CODESTR = #CODESTR + '#' + #ColumnName
if #CurrentDelimiterPositionVar <= #Count
BEGIN
IF #CurrentDelimiterPositionVar <> #Count
set #CODESTR = #CODESTR + ' , --type of ' + #DataType --all others with comma
else
set #CODESTR = #CODESTR + ' --type of ' + #DataType --the last one without comma
END -- IF SHOULD NOT PRINT COLUMN
--increase the counter
set #CODESTR = #CODESTR + CHAR(13)
SET #CurrentDelimiterPositionVar = #CurrentDelimiterPositionVar + 1;
END
set nocount off
SET #CODESTR = #CODESTR + ')
SET #' + #pkColumnName + ' = ##IDENTITY
set #Ret = ##ERROR
set #DebugMsgOut = ''TODO:REMOVE INSERT OK ''
END TRY
BEGIN CATCH
EXEC #ret = [dbo].[procUtils_GetMsgTxtByKeyAndUserSessionId]
#UserSessionId = 2,
#MsgKey = N''ErrorMsgMenuRetrievalFailed'',
#MsgTxt = #MsgOut OUTPUT
set #ret = 1
set #msgOut = #MsgTxt
set #debugMsgOut = '' Error number: '' + CAST(ERROR_NUMBER() AS varchar(100)) +
''Error message: '' + ERROR_MESSAGE() + ''Error severity: '' +
CAST(ERROR_SEVERITY() AS varchar(10)) +
''Error state: '' + CAST(ERROR_STATE() AS varchar(100)) +
''XACT_STATE: '' + CAST(XACT_STATE() AS varchar(100))
-- record the error in the database
set #debugMsgOut = #debugMsgOut + #msgOut
INSERT INTO [dbo].[LogStore] ( [Date],[Thread],[Level],[Logger],[Message])
values ( getdate() , N''8'', N''DEBUG'', #thisProcName , #debugMsgOut )
END CATCH
END --procedure end
GO
'
print #codestr
END TRY --end try
BEGIN CATCH
print ' Error number: ' + CAST(ERROR_NUMBER() AS varchar(100)) +
'Error message: ' + ERROR_MESSAGE() + 'Error severity: ' +
CAST(ERROR_SEVERITY() AS varchar(1000)) +
'Error state: ' + CAST(ERROR_STATE() AS varchar(100)) +
'XACT_STATE: ' + CAST(XACT_STATE() AS varchar(100))
END CATCH
END --procedure end
--USE [Gaf]
--GO
--SELECT NAME FROM SYS.tables where name like '%Msg%'
--EXEC [dbo].[procUtils_GenerateInsertProc] #TableName = N'Whatever'
GO

How to pass datetime in dynamic query in sql?

I have written a stored procedure like this
ALTER PROCEDURE [dbo].[spLoadPendingPaymentSheetByFilter] --'2015-04-01','2015-04-02','Select-One','Select-One','Select-One',''
#FromDate as datetime,
#ToDate as datetime,
#Status as nvarchar(50),
#Remarks as nvarchar(50),
#Paymenttype as nvarchar(50),
#BillID as nvarchar(50)
AS
Declare #Where as nvarchar(max)
set #Where = '( MenifestDate BETWEEN ''' + CONVERT(VARCHAR(10),#FromDate, 101) + ''' and ''' + CONVERT(VARCHAR(10),#ToDate, 101) + ''' )'
if(#Status <> 'Select-One')
set #Where = 'Status = '+ #Status
if(#Remarks <> 'Select-One')
set #Where = #Where + 'and Remarks = '+ #Remarks
if(#Paymenttype <> 'Select-One')
set #Where = #Where + 'and PaymentType = ' + #Paymenttype
if(#BillID <> '')
set #Where = #Where + 'and BillID = '+ #BillID
Declare #SelectString as nvarchar(1000)
set #SelectString = 'SELECT MasterID,BillID, MenifestDate, FarwardingNo,ReceverCountryName,Status,Remarks,PaymentType
FROM tblMenifest
WHERE ' + #Where
exec #SelectString
When I execute it I got this error
The name 'SELECT MasterID,BillID, MenifestDate, FarwardingNo,ReceverCountryName,Status,Remarks,PaymentType FROM tblMenifest WHERE ( MenifestDate BETWEEN '04/01/2015' and '04/02/2015' )' is not a valid identifier
The MenifestDate column datatype is datetime.
I believe that you want to put EXEC(#SelectString) rather than exec #SelectString.

Invalid Column Name '#FileName-- value'

I am getting 'Invalid Column Name '#FileName-- value'' ERROR WHILE executing below stored procedure. I tried to find the root cause of the issue with no luck...Please suggest me where i am wrong.
ALTER PROCEDURE [dbo].[usp_ICLExtract_GetFile]
#FileName Varchar(50),
#Image_Path Varchar(50) Output,
#FIleNameList varchar(4096) OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE #strProcName varchar(255)
SET #strProcName = 'usp_ICLExtract_GetFile'
DECLARE #strSQL1 varchar(1024), #strSQL2 varchar(1024)
DECLARE #strFileName Varchar(50)
DECLARE #intErrorReturn int
SET #intErrorReturn = 0
SET #FileNameList = ''
SET #Image_Path = ''
SET #strSQL1 = N'SELECT tbl_ICLExtCashLetter.Image_Path from tbl_ICLExtCashLetter INNER JOIN tbl_ICLExtFile on [tbl_ICLExtCashLetter].ICLExtFileUID = [tbl_ICLExtFile].ICLExtFileUID where tbl_ICLExtFile.FileName = ' + #FileName --This line cause error
/*==============================================================================
* Run the query'
*==============================================================================*/
SET #strSQL2 = 'DECLARE curCategory INSENSITIVE SCROLL CURSOR FOR ' + #strSQL1
EXEC(#strSQL2)
SELECT #intErrorReturn = ##ERROR
IF (#intErrorReturn <> 0) GOTO usp_ICLExtract_GetFile_Error
OPEN curCategory
SELECT #intErrorReturn = ##ERROR
IF (#intErrorReturn <> 0) GOTO usp_ICLExtract_GetFile_Error
FETCH NEXT FROM curCategory INTO #strFileName
WHILE (##FETCH_STATUS <> -1)
BEGIN
SET #FileNameList = #FileNameList + #strFileName + ';'
SET #Image_Path = #Image_Path + 1
FETCH NEXT FROM curCategory INTO #strFileName
END
CLOSE curCategory
DEALLOCATE curCategory
RETURN(0)
usp_ICLExtract_GetFile_Error:
RETURN(#intErrorReturn)
END
replace line with this
SET #strSQL1 = N'SELECT tbl_ICLExtCashLetter.Image_Path from tbl_ICLExtCashLetter INNER JOIN tbl_ICLExtFile on [tbl_ICLExtCashLetter].ICLExtFileUID = [tbl_ICLExtFile].ICLExtFileUID where tbl_ICLExtFile.FileName = ''' + #FileName +'''
Change your query to this:
N'SELECT tbl_ICLExtCashLetter.Image_Path from tbl_ICLExtCashLetter
INNER JOIN tbl_ICLExtFile on [tbl_ICLExtCashLetter].ICLExtFileUID =
[tbl_ICLExtFile].ICLExtFileUID where tbl_ICLExtFile.FileName = ''' + #FileName + ''''
you have to pass value between apostrophes '.