SQL Geo-Spatial Linked Server Query - c#

I have one question on the TSQL Linked Server Query. Linked Server is GIS enforced so we pass the coordinates to that server which it returns the data from the Linked Server. Please find the below-working query.
DECLARE #input varchar(max), #sql varchar(max);
SET #input = N'((-119.470830216356 46.2642458295079,-119.470722927989 46.2642050348762,-119.470076515615 46.2647075484513,-119.470240130371 46.2647075484512,-119.470830216356 46.2642458295079))'
BEGIN
SELECT #sql = 'select * from openquery([LinkedServerName],''DECLARE #b geometry;
SET #b = geometry::STGeomFromText(''''POLYGON '+ #input + ' '''', 4326);
SET #b = #b.MakeValid();
SELECT * from [Database].[Table] AS b
where b.Shape.STIntersects(#b.STCentroid()) = 1'')'
END
EXEC(#sql)
But the issue is sometimes we have to pass more than 8000 characters to the input parameter #input since it is varchar(max) and EXEC command both have an 8000 character limitation. So we are trying to get rid of Dynamic SQL so that we can pass the input using 2 input variables (We have implemented splitting the input into subsets each of 8000 characters in our C# code and sending them as 2 different inputs to the SQL Query). We have tried the below query in the Actual Server (Linked Server) which is working fine.
DECLARE #b geometry
SET #input = N'((-119.470830216356 46.2642458295079,-119.470722927989 46.2642050348762,'
SET #input2 = N'-119.470076515615 46.2647075484513,-119.470240130371 46.2647075484512,-119.470830216356 46.2642458295079))'
SELECT #b = geometry::STGeomFromText('POLYGON ' + #input + #input2 + '', 4326)
SELECT #b = #b.MakeValid()
SELECT * FROM [Database].[TableName] AS b
WHERE b.Shape.STIntersects(#b.STCentroid()) = 1
We tried below SQL Linked query in our local server but it is throwing below error
DECLARE #input varchar(max), #input2 varchar(max);
SET #input = N'((-119.470830216356 46.2642458295079,-119.470722927989 46.2642050348762,'
SET #input2 = N'-119.470076515615 46.2647075484513,-119.470240130371 46.2647075484512,-119.470830216356 46.2642458295079))'
SELECT * FROM OPENQUERY([LinkedServerName],
'DECLARE #b geometry;
SELECT #b = geometry::STGeomFromText(''''POLYGON ' + #input + #input2 + '' ', 4326);
SELECT #b = #b.MakeValid();
SELECT * FROM [DatabaseName].[TableName] AS b
where b.Shape.STIntersects(#b.STCentroid()) = 1') AS AD
In the above query, an issue has been highlighted in the attached image.
Help is really appreciated.

Related

SqlCommand Parameters.AddWithValue return # instead of variable [duplicate]

I am trying to execute this query:
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
This produces the following error:
Msg 1087, Level 16, State 1, Line 5
Must declare the table variable "#tablename".
What's the right way to have the table name populated dynamically?
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table and schema, I have created this dynamic query:
declare #schema sysname;
declare #table sysname;
declare #query nvarchar(max);
set #schema = 'dbo'
set #table = 'ACTY'
set #query = '
SELECT * FROM [DB_ONE].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table) + '
EXCEPT
SELECT * FROM [DB_TWO].' + QUOTENAME(#schema) + '.' + QUOTENAME(#table);
EXEC sp_executesql #query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Change your last statement to this:
EXEC('SELECT * FROM ' + #tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE #table_name varchar(max)
SET #table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = #table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + #table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + #table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
Use:
CREATE PROCEDURE [dbo].[GetByName]
#TableName NVARCHAR(100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #sSQL nvarchar(500);
SELECT #sSQL = N'SELECT * FROM' + QUOTENAME(#TableName);
EXEC sp_executesql #sSQL
END
You can't use a table name for a variable. You'd have to do this instead:
DECLARE #sqlCommand varchar(1000)
SET #sqlCommand = 'SELECT * from yourtable'
EXEC (#sqlCommand)
You'll need to generate the SQL content dynamically:
declare #tablename varchar(50)
set #tablename = 'test'
declare #sql varchar(500)
set #sql = 'select * from ' + #tablename
exec (#sql)
Use sp_executesql to execute any SQL, e.g.
DECLARE #tbl sysname,
#sql nvarchar(4000),
#params nvarchar(4000),
#count int
DECLARE tblcur CURSOR STATIC LOCAL FOR
SELECT object_name(id) FROM syscolumns WHERE name = 'LastUpdated'
ORDER BY 1
OPEN tblcur
WHILE 1 = 1
BEGIN
FETCH tblcur INTO #tbl
IF ##fetch_status <> 0
BREAK
SELECT #sql =
N' SELECT #cnt = COUNT(*) FROM dbo.' + quotename(#tbl) +
N' WHERE LastUpdated BETWEEN #fromdate AND ' +
N' coalesce(#todate, ''99991231'')'
SELECT #params = N'#fromdate datetime, ' +
N'#todate datetime = NULL, ' +
N'#cnt int OUTPUT'
EXEC sp_executesql #sql, #params, '20060101', #cnt = #count OUTPUT
PRINT #tbl + ': ' + convert(varchar(10), #count) + ' modified rows.'
END
DEALLOCATE tblcur
You need to use the SQL Server dynamic SQL:
DECLARE #table NVARCHAR(128),
#sql NVARCHAR(MAX);
SET #table = N'tableName';
SET #sql = N'SELECT * FROM ' + #table;
Use EXEC to execute any SQL:
EXEC (#sql)
Use EXEC sp_executesql to execute any SQL:
EXEC sp_executesql #sql;
Use EXECUTE sp_executesql to execute any SQL:
EXECUTE sp_executesql #sql
Declare #tablename varchar(50)
set #tablename = 'Your table Name'
EXEC('select * from ' + #tablename)
Also, you can use this...
DECLARE #SeqID varchar(150);
DECLARE #TableName varchar(150);
SET #TableName = (Select TableName from Table);
SET #SeqID = 'SELECT NEXT VALUE FOR ' + #TableName + '_Data'
exec (#SeqID)
Declare #fs_e int, #C_Tables CURSOR, #Table varchar(50)
SET #C_Tables = CURSOR FOR
select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN #C_Tables
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
WHILE ( #fs_e <> -1)
BEGIN
exec('Select * from ' + #Table)
FETCH #C_Tables INTO #Table
SELECT #fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '#C_Tables'
END

Using ExecuteNonQuery to run a Stored Procedure isn't creating my table, but the table is created when executing the sp in SSMS

Some notes:
ExecuteNonQuery returns -1
ExecuteNonQuery will drop the table (#droptable), but it will not create the new table (#code)
the length of the #code query is 10265 characters
The stored procedure runs perfectly fine in SSMS and returns 22 rows in the table
Are there any ideas as to why C#'s ExecuteNonQuery function doesn't seem to be executing the 'exec(#code)' portion of the stored procedure?
ALTER procedure [dbo].[sp_create_EditControlResultsPivot]
as
begin
declare #t nvarchar (250);
set #t = 'editControlResults'
declare #newtable nvarchar(250);
set #newtable = 'dbo.' + #t + 'Pivot'
declare #nonPivotColumn1 nvarchar(250);
set #nonPivotColumn1 = 'num'
declare #nonPivotColumn2 nvarchar(25);
set #nonPivotColumn2 = 'File_Name'
declare #droptable nvarchar(max);
set #droptable =
'if EXISTS (select * from sys.objects where object_id = object_id(N''' + #newtable + '''))
begin drop table ' + #newtable + ' end
'
declare #i int
set #i = 1;
declare #itemList nvarchar(max);
declare #code nvarchar(max);
while #i <= (
select COUNT(*)
from sys.columns c
left join sys.tables t on c.object_id = t.object_id
where 1=1
and c.name not like #nonPivotColumn1
and c.name not like #nonPivotColumn2
and t.name = #t
)
begin
set #itemList = #itemList + ', ' +
(
select col from
(
select c.name as col, ROW_NUMBER () over (order by c.name) as num from
sys.columns c left join sys.tables t on c.object_id = t.object_id
where 1=1
and c.name not like #nonPivotColumn1
and c.name not like #nonPivotColumn2
and t.name = #t
) sub where num = #i
)
set #i = #i + 1
end
set #itemList = (select substring(#itemList, 2, LEN(#itemList)))
set #code = '
SELECT ' + #nonpivotcolumn2 + ', Item
into ' + #newtable + '
FROM
(SELECT ' + #nonpivotcolumn2 + ', ' + #itemList + '
FROM ' + #t + ') sub
UNPIVOT
(Value FOR Item IN (' + #itemList + ')
) AS sub
where Value = ''true''
'
exec(#droptable)
exec(#code);
--print(len(#code))
END
--exec sp_create_EditControlResultsPivot
The ExecuteNonQuery Method returns the number of rows affected use the ExecuteReader method instead.
SqlCommand.ExecuteReader Method
The only way to return data from ExecuteNonQuery would be via an Output parameter.
I suspect your comment #3. the length of the #code query is 10265 characters...could be an issue...I think the call from C# is chopping it to only 4000 or 8000 chars...
Since you are not expecting a resultset, ExecuteNonQuery is good.
Things to try:
Try inserting the content of the #code variable (inside the procedure) in a table and see if you are getting the correct sql...both when executed from SSMS and from C# call
If you get a valid sql query in step 1 (which I doubt)...try executing that query in SSMS to see if it really works...

Stored Procedure giving different result on same database with same argument

I have a stored procedure which gives different result in only a specific case.
When I call it from SQL Server Management Studio 2008 R2, it gives me 0 as output.
When I call it from C# class file. It gives me 1 as output.
I am using edmx file, and it is updated for sure.
The call is something like below from SSMS [SQL Server Management Studio]
exec proc_GetPrimaryKeyUsageCount 62, 'tblFormula'
This gives output as 0
The same stored procedure is called from C# file is like below
_db.GetPrimaryKeyUsageCount(62, "tblFormula");
This gives output as 1
The stored procedure is
CREATE PROCEDURE proc_GetPrimaryKeyUsageCount (
#PrimaryKeyColumnId INT
,#PrimaryKeyTable NVARCHAR(max)
--,#Response INT OUTPUT
)
AS
BEGIN
DECLARE #counter INT
DECLARE #sqlCommand NVARCHAR(max)
DECLARE #ForeignKey TABLE (
child_table VARCHAR(max)
,child_fk_column VARCHAR(max)
)
DECLARE #child_table VARCHAR(max)
DECLARE #child_fk_column VARCHAR(max)
SET #counter = 0
INSERT INTO #ForeignKey
SELECT child_table = c.TABLE_NAME
,child_fk_column = c.COLUMN_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE p
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS pc ON pc.UNIQUE_CONSTRAINT_SCHEMA = p.CONSTRAINT_SCHEMA
AND pc.UNIQUE_CONSTRAINT_NAME = p.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c ON c.CONSTRAINT_SCHEMA = pc.CONSTRAINT_SCHEMA
AND c.CONSTRAINT_NAME = pc.CONSTRAINT_NAME
WHERE EXISTS (
SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'IsDeleted'
AND TABLE_SCHEMA = p.TABLE_SCHEMA
AND TABLE_NAME = p.TABLE_NAME
AND p.TABLE_NAME = #PrimaryKeyTable
)
DECLARE db_cursor CURSOR
FOR
SELECT child_table
,child_fk_column
FROM #ForeignKey
OPEN db_cursor
FETCH NEXT
FROM db_cursor
INTO #child_table
,#child_fk_column
WHILE ##FETCH_STATUS = 0
BEGIN
PRINT 'select count(*) from ' + CAST(#child_table AS VARCHAR) + ' where ' + CAST(#child_fk_column AS VARCHAR) + ' = ' + CAST(#PrimaryKeyColumnId AS VARCHAR)
SET #sqlCommand = 'select #cnt=count(*) from ' + CAST(#child_table AS VARCHAR) + ' where ' + CAST(#child_fk_column AS VARCHAR) + ' = ' + CAST(#PrimaryKeyColumnId AS VARCHAR)
EXEC sp_executesql #sqlCommand
,N'#cnt int OUTPUT'
,#cnt = #counter OUTPUT
IF #counter > 0
BREAK
FETCH NEXT
FROM db_cursor
INTO #child_table
,#child_fk_column
END
SELECT #counter AS [PrimaryKeyUsageCount]
END
1st argument is Id of the primary key and 2nd argument is the name of the table having that primary key.
The Procedure returns the count of the usage of primary key in other tables in same database. If it finds even 1 occurrence, it will return that count otherwise 0.
If anything extra is needed please do let me know.
There are couple of mistakes, which could cause the problem.
The INSERT should be like that:
INSERT INTO #ForeignKey
SELECT c.TABLE_NAME,c.COLUMN_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE p
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS pc ON pc.UNIQUE_CONSTRAINT_SCHEMA = p.CONSTRAINT_SCHEMA
AND pc.UNIQUE_CONSTRAINT_NAME = p.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c ON c.CONSTRAINT_SCHEMA = pc.CONSTRAINT_SCHEMA
AND c.CONSTRAINT_NAME = pc.CONSTRAINT_NAME
WHERE EXISTS (
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS AS isc
WHERE isc.COLUMN_NAME = 'IsDeleted'
AND isc.TABLE_SCHEMA = p.TABLE_SCHEMA
AND isc.TABLE_NAME = p.TABLE_NAME
AND p.TABLE_NAME = #PrimaryKeyTable
)
After cursor loop shoud be:
CLOSE db_cursor
DEALLOCATE db_cursor

SQL execute string issue with National language character?

i have a simple sp in sql as bellow :
alter proc sptest(#val nvarchar(30))
as
select COUNT(*) from AAtable
where name = #val
as i call this sp with #val = 'مریم', it works well and returns value.
but when i change it like this :
alter proc sptest(#val nvarchar(30))
as
declare #q nvarchar(max)
set #q = 'select COUNT(*) from AAtable where name = ' + #val
Execute(#q)
and call it with the same #val, it converts #val value to "?" and returns error. i should say that #val comes from a string parameter in c#. as i know .net convert string to nvarchar parameter form sql. anyway i can not add N before #val.
and also i HAVE to make a string query and execute it so i can not change it to the first code too.
if i do this : set #q = 'select COUNT(*) from AAtable where name = N''' + #val + '''' it does not work too.
why execute string makes my nvarchar parameter to "?" !?
Add the N in front of your text, so it is an NVARCHAR literal, not a VARCHAR, like this: N'My Text'
Try marking the first string of your concatenation operation as explicit Unicode:
set #q = N'select COUNT(*) from AAtable where name = ' + #val
This should keep your #val in Unicode as well.
ALTER proc sptest(#val nvarchar(30))
AS
DECLARE #retval INT
DECLARE #SQLString nvarchar(500);
DECLARE #ParmDefinition nvarchar(500);
SET #SQLString =
N'select #retvalOUT = COUNT(*) from AAtable where name = #Name';
SET #ParmDefinition = N'#Name varchar(30), retvalOUT int OUTPUT';
EXECUTE sp_executesql #SQLString, #ParmDefinition,
#Name = #val,
#retvalOUT=#retval OUTPUT;
SELECT #retval;

Linq to sql unkown return types stored procedure .dbml

ALTER PROCEDURE [dbo].[uspGetBusesByDepature]
-- Add the parameters for the stored procedure here
#vRouteNumber varchar(4),
#dtDepartureTime datetime,
#dtArrivalTime datetime,
#InDate datetime
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #DeparturePoint geography,
#Latitude float,
#Longitude float,
#Radius float
-- Insert statements for procedure here
SET #Latitude = (SELECT fRouteWayPointLatitude
FROM dbo.RouteWayPoint
WHERE vRouteNumber = #vRouteNumber
AND iSequence = 1)
SET #Longitude = (SELECT fRouteWayPointLongitude
FROM dbo.RouteWayPoint
WHERE vRouteNumber = #vRouteNumber
AND iSequence = 1)
SET #Radius = (SELECT fRouteWayPointRadius
FROM dbo.RouteWayPoint
WHERE vRouteNumber = #vRouteNumber
AND iSequence = 1) * 1000
SET #DeparturePoint = geography::Point(#Latitude, #Longitude, 4326)
SET #dtDepartureTime = CONVERT(varchar, #InDate, 101) + ' ' + CONVERT(varchar(8), #dtDepartureTime, 108)
SELECT gps.iVehicleID, sDesc AS vVehicleDescription, sRegNo AS [vVehicleRegNo],
SUBSTRING(CONVERT(varchar(8), MIN(dtTime), 108), 1, 5)
+ ' | ' + SUBSTRING(sDesc, 1, 4) + ' - ' +
SUBSTRING(sRegNo, 1, CHARINDEX('-',sRegNo,1)-1)
AS vVehicleText, MIN(dtTime) AS dtTime--,
--dbo.fnBusIsAssigned(gps.iVehicleID, #dtDepartureTime, #dtArrivalTime, #InDate) AS isAssigned
FROM dbo.GPSDataDW gps INNER JOIN Vehicles v
ON gps.iVehicleID = v.iVehicleID
WHERE dtTime BETWEEN DATEADD(MI, -30, #dtDepartureTime) AND DATEADD(MI, 30, #dtDepartureTime)
AND #Radius > #DeparturePoint.STDistance(geography::Point(fLatitude, fLongitude, 4326))
GROUP BY gps.iVehicleID, sDesc, sRegNo
END
Any one who can help me with this error I check everything I don't seem to be calling/returning multiple table at once.
Thanks in advance.
Good day,
I found my problem. The problem was the geography data type which was causing this problem. After I commented this line out:-
SET #DeparturePoint = geography::Point(#Latitude, #Longitude, 4326);
everything went well, I don't know why is that.

Categories

Resources